0

Is there a way to reduce an iterable object to a single value? In javascript this can be done like so:

var array = [{num: 1}, {num: 10}, {num: 5}];

var result = array.reduce((cur, val) => val.num > cur ? val.num : cur, 0);
    
console.log(result);

The above will return the largest number in the array of objects.

Currently in C# I am using a foreach to find the largest item, but is there a built in function similar to the javascript reduce method from above?

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338

1 Answers1

2

The equivalent of reduce in LINQ is Aggregate

var nums = Enumerable.Range(0, 10);

var max = nums.Aggregate(Int32.MinValue, (acc,elem) => acc < elem ? elem : acc);
Jonathon Chase
  • 9,396
  • 21
  • 39
  • Aggregate only takes one argument in 3.1, so you can't chose the result value type – roberto tomás Mar 09 '20 at 14:15
  • @robertotomás Are you sure about this? [This](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregate?view=netcore-3.1#System_Linq_Enumerable_Aggregate__3_System_Collections_Generic_IEnumerable___0____1_System_Func___1___0___1__System_Func___1___2__) looks to be the same seeded overload. – Jonathon Chase Mar 09 '20 at 14:18
  • I'm sorry, this may be specific to a raw array like MyObjects[] .. I have a Dictionary and calling dict.Values.Aggregate gives me the error I had mentioned. – roberto tomás Mar 09 '20 at 14:37
  • @robertotomás Values is a list of lists in that case. You may need to flatten it with `SelectMany(x => x)` before you aggregate. – Jonathon Chase Mar 09 '20 at 14:38