Adding C# solution.
[IEnumerableExtras.git] / C# / EnumerableReduce.cs
blob74380c666c60a471e14edf2023343509ad4c29d2
1 using System;
2 using System.Collections;
3 using System.Collections.Generic;
5 namespace IEnumerableExtras
7 /// <summary>
8 /// <see cref="IEnumerable{T}"/> reduce extension.
9 /// </summary>
10 public static class EnumerableReduce
12 /// <summary>
13 /// Reduce this instance of <see cref="IEnumerable{TValue}"/> to a single value of
14 /// type <typeparamref name="TValue"/> using given predicate.
15 /// </summary>
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)
23 bool first = true;
24 TValue result = default(TValue);
26 foreach (TValue value in collection)
28 if (first)
30 result = value;
31 first = false;
33 else
35 result = predicate(result, value);
39 return result;
42 /// <summary>
43 /// Reduce this instance of <see cref="IEnumerable{TValue}"/> to a single value of
44 /// type <typeparamref name="TValue"/> using given predicate.
45 /// </summary>
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 )
53 bool first = true;
54 TValue result = default( TValue );
56 foreach ( TValue value in collection )
58 if ( first )
60 result = value;
61 first = false;
63 else
65 result = predicate( result, value );
69 return result;
72 /// <summary>
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"/>.
76 /// </summary>
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 );
91 return init;