You can write your own extension method that ends the call to IEnumerable<T>.Aggregate , which in turn calls your overloaded operator + :
public static MyClass Sum(this IEnumerable<MyClass> collection) { return collection.Aggregate((a, b) => a + b); }
This will be called:
MyClass sum = myClasses.Sum();
Or even take another step, summarize and enable the selector:
public static MyClass Sum<T>(this IEnumerable<T> collection, Func<T, MyClass> selector) { return collection.Aggregate(new MyClass() /*start with an empty MyClass*/, (a, b) => a + selector(b)); }
This will be triggered as you suggest:
MyClass sum = myClasses.Sum(d => d);
Like complex types containing MyClass , for example:
class Foo { public MyClass Bar {get; set;} public int Baz {get; set;} } var FooList = new List<Foo>(); MyClass sumOfFooListsBars = FooList.Sum(f => f.Bar);
source share