Handy EnumerableExtensions
There’s a great site for finding extension methods, ExtensionMethod.net. I don’t believe either of these came from there, and I’ve not (yet) submitted them there, but here are a couple of extensions on IEnumerable<T> that I’ve found useful recently.
ForEach<T>
The first one is simply a method that allows you to easily iterate over a sequence and perform an action on it. This is a pretty commonly useful extension method, so much so that it’s now included in .NET 4.0 out of the box. But if you’re using an older version of the framework, this is one you can roll yourself.
public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (T item in items)
{
action(item);
}
}
ContainsAny<T>
If you have a collection, you can test for whether it contains an item by using the .Contains(T item) extension method. However, this only works for single instances of an item. What if you have a set of items and you need to know if that set contains any elements of a second set of items? For that, you want to use ContainsAny(), which you can use with either a params collection (specify each item inline) or with an enumerable parameter. Here are the methods:
public static bool ContainsAny<T>(this IEnumerable<T> sequence, params T[] matches)
{
return matches.Any(value => sequence.Contains(value));
}
public static bool ContainsAny<T>(this IEnumerable<T> sequence, IEnumerable<T> matches)
{
return matches.Any(value => sequence.Contains(value));
}
And here are some passing unit tests that demonstrate how these are used:
[TestFixture]
public class ContainsAnyShould
{
[Test]
public void ReturnTrueGivenMatchInItemCollection()
{
var testList = new List<string>() { "A", "B", "C" };
var filterList = new List<string>() { "C", "D", "E" };
Assert.IsTrue(testList.ContainsAny(filterList));
}
[Test]
public void ReturnFalseGivenNoMatchInItemCollection()
{
var testList = new List<string>() { "A", "B", "C" };
var filterList = new List<string>() { "D", "E" };
Assert.IsFalse(testList.ContainsAny(filterList));
}
[Test]
public void ReturnTrueGivenMatchInParamCollection()
{
var testList = new List<string>() { "A", "B", "C" };
Assert.IsTrue(testList.ContainsAny("C", "D", "E"));
}
[Test]
public void ReturnFalseGivenNoMatchInParamCollection()
{
var testList = new List<string>() { "A", "B", "C" };
Assert.IsFalse(testList.ContainsAny("D", "E"));
}