Linq: ContainsAtLeast and AggregationOrDefault
I've created a couple of useful extension methods that I like to use with Linq, so here they are:
ContainsAtLeast
I've noticed that there's no way to find out whether a collection has at least X items. The following takes the collection, tries to take X items from it and asks whether it succeeded or not:
public static bool ContainsAtLeast<T>(this IEnumerable<T> enumeration,
int count)
{
// Check to see that enumeration is not null
if (enumeration == null)
throw new ArgumentNullException("enumeration");
return (from t in enumeration.Take(count)
select t)
.Count() == count;
}
AggregationOrDefault
When I need the first item in a collection, I love using First when I need an exception and FirstOrDefault when I don't. However, this doesn't exist for aggregations and if your collection is empty, Max, Min, etc. will throw an exception.
public static T AggregationOrDefault<T>(this IEnumerable<T> enumeration,
Func<IEnumerable<T>, T> aggregationMethod)
{
// Check to see that enumeration is not null
if (enumeration == null)
throw new ArgumentNullException("enumeration");
// Check to see that aggregationMethod is not null
if (aggregationMethod == null)
throw new ArgumentNullException("aggregationMethod");
if (!enumeration.ContainsAtLeast(1))
return default(T);
return aggregationMethod(enumeration);
}
What this does is take a collection and an aggregation method, checks whether there's at least one item and applies the method. This is very useful, because most aggregation methods that take only one parameter - the collection, are not generic, so that would mean, just like in Linq itself, creating a copy of this method for every numeric type (as an example, see Max<T> compared to Max).
How to use it? Simple:
myEnumeration.AggregationOrDefault(Enumerable.Max);
In this case, sending the Max method to AggregationOrDefault.