Quick question, what\'s the preferable way to programmaticaly ask \"Is there exactly one element in this sequence that satisfies X condition?\" using Linq?
i.e.
Once I had the issue to determine if exactly one item is contained I decided to create following extension. In my optionion it fits good into the set of already existing extensions (e.g.: SingleOrDefualt, FirstOrDefault ...).
public static class IEnumerableExtension
{
public static TProject OneOrDefault(this IEnumerable sequence, Func projection)
{
var enumerator = sequence.GetEnumerator();
bool firstMoveNext = enumerator.MoveNext();
TInput current = enumerator.Current;
if (firstMoveNext && !enumerator.MoveNext())
{
return projection(current);
}
else
{
return default;
}
}
}