I\'m getting an exception whenever I fetch like this
Feature f = o.Features.SingleOrDefault(e => e.LinkName == PageLink);
because this can r
I've found I need the behavior of returning a default value if there is not exactly one element (i.e. zero, two, or more) more often than I need the normal SingleOrDefault
behavior, so here's my adapted version of Pieter van Ginkel's answer:
public static class LinqExtensions
{
/// <summary>
/// Returns the only element of a sequence, or a default value if the sequence is empty or contains more than one element.
/// </summary>
public static TSource SingleOrDefaultIfMultiple<TSource>(this IEnumerable<TSource> source)
{
var elements = source.Take(2).ToArray();
return (elements.Length == 1) ? elements[0] : default(TSource);
}
/// <summary>
/// Returns the only element of a sequence, or a default value if the sequence is empty or contains more than one element.
/// </summary>
public static TSource SingleOrDefaultIfMultiple<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
return source.Where(predicate).SingleOrDefaultIfMultiple();
}
/// <summary>
/// Returns the only element of a sequence, or a default value if the sequence is empty or contains more than one element.
/// </summary>
public static TSource SingleOrDefaultIfMultiple<TSource>(this IQueryable<TSource> source)
{
var elements = source.Take(2).ToArray();
return (elements.Length == 1) ? elements[0] : default(TSource);
}
/// <summary>
/// Returns the only element of a sequence, or a default value if the sequence is empty or contains more than one element.
/// </summary>
public static TSource SingleOrDefaultIfMultiple<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
{
return source.Where(predicate).SingleOrDefaultIfMultiple();
}
}
I've omitted the null argument checks because I'm OK with relying on the Take
and Where
calls to throw exceptions when the arguments are null, but you might feel otherwise.