tags:

views:

83

answers:

2

How to apply a function to every element in a list using Linq in C# like the method reduce() in python?

+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
+1 - once I figured out what reduce() did...
hunter
I didn't know either :)
Cory Larson
+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