2 using System
.Collections
;
3 using System
.Collections
.Generic
;
5 namespace IEnumerableExtras
8 /// <see cref="IEnumerable{T}"/> reduce extension.
10 public static class EnumerableReduce
13 /// Reduce this instance of <see cref="IEnumerable{TValue}"/> to a single value of
14 /// type <typeparamref name="TValue"/> using given predicate.
16 /// <typeparam name="TValue"></typeparam>
17 /// <param name="collection"></param>
18 /// <param name="predicate"></param>
19 /// <returns></returns>
20 public static TValue Reduce
<TValue
>(this IEnumerable collection
,
21 Func
<TValue
, TValue
, TValue
> predicate
)
24 TValue result
= default(TValue
);
26 foreach (TValue
value in collection
)
35 result
= predicate(result
, value);
43 /// Reduce this instance of <see cref="IEnumerable{TValue}"/> to a single value of
44 /// type <typeparamref name="TValue"/> using given predicate.
46 /// <typeparam name="TValue"></typeparam>
47 /// <param name="collection"></param>
48 /// <param name="predicate"></param>
49 /// <returns></returns>
50 public static TValue Reduce
< TValue
>( this IEnumerable
<TValue
> collection
,
51 Func
<TValue
, TValue
, TValue
> predicate
)
54 TValue result
= default( TValue
);
56 foreach ( TValue
value in collection
)
65 result
= predicate( result
, value );
73 /// Reduce this instance of <see cref="IEnumerable{TValue}"/> to a single value of
74 /// type <typeparamref name="TResult"/> using given predicate and an initial value
75 /// of type <typeparamref name="TResult"/>.
77 /// <typeparam name="TValue"></typeparam>
78 /// <typeparam name="TResult"></typeparam>
79 /// <param name="collection"></param>
80 /// <param name="init"></param>
81 /// <param name="predicate"></param>
82 /// <returns></returns>
83 public static TResult Reduce
< TValue
, TResult
>( this IEnumerable
<TValue
> collection
, TResult init
,
84 Func
<TResult
, TValue
, TResult
> predicate
)
86 foreach ( TValue
value in collection
)
88 init
= predicate( init
, value );