ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Aggregate

Since System.Linq.Enumerable.Aggregate throws a System.InvalidOperationException in case the given list is empty you can't use this function in a complex linq expression. This aggregate version simply returns a defaultvalue if the list is empty

Source

namespace ExtensionMethods
{
	public static class Enumerable
	{
		public static T Aggregate<T>(
			this IEnumerable<T> list, Func<T, T, T> aggregateFunction)
		{
			return Aggregate<T>(list, default(T), aggregateFunction);
		}

		public static T Aggregate<T>(this IEnumerable<T> list, T defaultValue,
			Func<T, T, T> aggregateFunction)
		{
			return list.Count() <= 0 ?
				defaultValue : list.Aggregate<T>(aggregateFunction);
		}
	}
}

Example

return (  from x in _map.Keys
	  where CheckValue(x)
	  select _map[x]).			    Aggregate(MyFlags.None, (x, y) => x | y);

Author: RW

Submitted on: 18 feb. 2009

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 8109