[Test]
public void CanAggregateIdAndValue()
{
var idValuePairs = new List<IdValuePair>
{
new IdValuePair(1, 1),
new IdValuePair(1, 2),
new IdValuePair(1, 3),
new IdValuePair(2, 1),
new IdValuePair(2, 2),
new IdValuePair(3, 1),
new IdValuePair(4, 1),
new IdValuePair(4, 2)
};
var expectedAggregatedIdValuePairs = new List<IdValuePair>
{
new IdValuePair(1, 6),
new IdValuePair(2, 3),
new IdValuePair(3, 1),
new IdValuePair(4, 3)
};
var aggregatedIdValuePairs = Aggregate(idValuePairs);
Assert.IsTrue(expectedAggregatedIdValuePairs.SequenceEqual(aggregatedIdValuePairs));
}
private static IEnumerable<IdValuePair> Aggregate(IEnumerable<IdValuePair> idValuePairs)
{
// imperative OO
/*var map = new Dictionary<int, int>();
foreach (var idValuePair in idValuePairs)
{
if (map.Keys.Contains(idValuePair.Key))
{
map[idValuePair.Key] += idValuePair.Value;
}
else
{
map[idValuePair.Key] = idValuePair.Value;
}
}
foreach (var aggregatedIdValuePair in map)
{
yield return aggregatedIdValuePair;
}*/
// declarative linq
return (from ivp in idValuePairs
group ivp by ivp.Key into aggregateGroup
select new IdValuePair(aggregateGroup.Key, aggregateGroup.Sum(x => x.Value)));
}
No comments:
Post a Comment