How to apply a function to every element in a list using Linq in C# like the method reduce() in python?
views:
83answers:
2
+9
A:
Assuming you're talking about this reduce function, the equivalent in C# and LINQ is Enumerable.Aggregate.
Quick example:
var list = Enumerable.Range(5, 3); // [5, 6, 7]
Console.WriteLine("Aggregation: {0}", list.Aggregate((a, b) => (a + b)));
// Result is "Aggregation: 18"
Cory Larson
2010-09-29 19:41:02
+1 - once I figured out what reduce() did...
hunter
2010-09-29 19:43:04
I didn't know either :)
Cory Larson
2010-09-29 19:53:57
+2
A:
Enumerable.Aggregate is your answer. reduce(function, list, seed) ==> list.Aggregate(seed, function). In addition, there are many predefined "aggregates", like Sum, Min, Max, Average, etc. You should use Aggregate only when the aggregator is not built-in.
KeithS
2010-09-29 19:45:55