Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiplying list<int> with number in C#

Is the only way you can multiply an integer list in C# with a value, by using a loop through the items?
I have been searching for ways to avoid loops, but with no luck.
I know in Python, for example you do not have to loop through a list to do this, so I was wondering if there is any way in C# as well to achieve the following:

  List<int> myList = new List<int>() { 1, 2, 3 };
  
  int mult = 5;

  foreach(int i in myList)
     mult = mult * i;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You could use LINQ’s Aggregate to do this:

List<int> myList = new List<int>() { 1, 2, 3 };
int mult = myList.Aggregate(5, (cur, val) => cur * val);
Console.WriteLine(mult); // prints 30

But note that this still uses a loop internally. Python will also use a list internally, even if it isn’t apparent to you.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading