As some astute readers pointed out, this functionality does in fact exist in LINQ. The name isn’t terribly obvious however: Aggregate. I was able to update the original tests to use the Aggregate method. The main difference is that a non-generic IEnumerable does not contain this functionality. For that type I had to use:
.OfType<>()
The updated test methods are here:
IEnumerable<string> collection = new[] { "Hello", "World", "!" };
string result = collection.Aggregate((str1, str2) => (str1 + " " + str2).Trim());
IEnumerable<int> collection = new[] { 1, 2, 3, 4, 5 };
int result = collection.Aggregate((num1, num2) => num1 + num2);
IEnumerable collection = new[] { "Hello", "World", "!" };
string result = collection.OfType<string>().Aggregate((string str1, string str2) => (str1 + " " + str2).Trim());
var collection = new List<string> { "Hello", "World", "!" };
string result = collection.Aggregate((str1, str2) => (str1 + " " + str2).Trim());
I love learning new stuff, thanks to Steve Gilham and Jordan Terrell for their comments below.
I really like the Each function in jQuery, and I find myself wanting to use it in LINQ. Since it doesn’t exist I decided to write one. Here goes:
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public static class ExtensionMethods
{
public static TType Each<TType>(this IEnumerable<TType> collection, Func<TType, TType, TType> func)
{
var result = default(TType);
foreach (var queryable in collection)
result = func(result, queryable);
return result;
}
public static TType Each<TType>(this IEnumerable collection, Func<TType, TType, TType> func)
{
return collection.OfType<TType>().Each(func);
}
}
You can then call these extension methods using any IEnumerable type, such as List, Collection, etc. I’m utilizing lambdas to define inline methods, though a delegate to an existing method could be passed in as well.
IEnumerable<string> collection = new[] { "Hello", "World", "!" };
string result = collection.Each((str1, str2) => (str1 + " " + str2).Trim());
IEnumerable<int> collection = new[] { 1, 2, 3, 4, 5 };
int result = collection.Each((num1, num2) => num1 + num2);
IEnumerable collection = new[] { "Hello", "World", "!" };
string result = collection.Each((string str1, string str2) => (str1 + " " + str2).Trim());
var collection = new List<string> { "Hello", "World", "!" };
string result = collection.Each((str1, str2) => (str1 + " " + str2).Trim());
What do you think? Would you do it differently?