Skip to content

Instantly share code, notes, and snippets.

@gprasant
Created May 1, 2012 14:19
Show Gist options
  • Save gprasant/2568221 to your computer and use it in GitHub Desktop.
Save gprasant/2568221 to your computer and use it in GitHub Desktop.
Shows how Enumerable.Aggregate can be used
namespace IEnumerable.Tests
{
[TestClass]
public class TestAggregate
{
Func<int, int, int> sum = (a, b) => a + b;
[TestMethod]
public void ShouldAggregateAllElementsInASequence()
{
var sequence = Enumerable.Range(1, 2);
int total = sequence.Aggregate(sum);
Assert.AreEqual(total, 3);
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void ShouldAggregateOverAnEmptySequence()
{
var sequence = Enumerable.Empty<int>();
var total = sequence.Aggregate(sum);
}
[TestMethod]
public void ShouldAggregateOverElementsInASequenceGivenASeed()
{
var sequence = Enumerable.Range(1, 2);
var total = sequence.Aggregate(10, (a, b) => a + b);
Assert.AreEqual(total, 13);
}
[TestMethod]
public void ShouldAggregateAndSelectAValueFromFinalResult()
{
var sequence = Enumerable.Range(1, 2);
var total = sequence.Aggregate(0, sum, x => new{IntValue = x});
Assert.AreEqual(total.IntValue, 3);
}
}
}
//
namespace MyOwn.Linq
{
public static class Enumerable
{
public static T Aggregate<T>(this IEnumerable<T> source, Func<T, T, T> accumulator)
{
if (source == null)
throw new ArgumentException("source");
if (accumulator == null)
throw new ArgumentException("accumulator");
IEnumerator<T> enumerator = source.GetEnumerator();
T prev = enumerator.Current;
T current = default(T);
while (enumerator.MoveNext())
{
current = accumulator(prev, current);
}
return current;
}
public static T Aggregate<T>(this IEnumerable<T> source, T seed, Func<T, T, T> accumulator)
{
return default(T);
}
public static TResult Aggregate<TSource, TAccumulate, TResult>(this IEnumerable<TSource> source,
TAccumulate seed,
Func<TAccumulate, TSource, TAccumulate> func,
Func<TAccumulate, TResult> resultSelector)
{
if (source == null)
throw new ArgumentNullException("source");
if (func == null)
throw new ArgumentException("func");
if (resultSelector == null)
throw new ArgumentNullException("resultSelector");
TAccumulate currentAccumulate = seed;
foreach (var item in source)
{
currentAccumulate = func(currentAccumulate, item);
}
return resultSelector(currentAccumulate);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment