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 :
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.