Efficient Linq Enumerable's 'Count() == 1' test

int constrainedCount = yourSequence.Take(2).Count();

// if constrainedCount == 0 then the sequence is empty
// if constrainedCount == 1 then the sequence contains a single element
// if constrainedCount == 2 then the sequence has more than one element

One way is to write a new extension method

public static bool IsSingle<T>(this IEnumerable<T> enumerable) {
  using (var enumerator = enumerable.GetEnumerator()) {
    if (!enumerator.MoveNext()) {
      return false;
    }
    return !enumerator.MoveNext();
  }
}

This code take's LukeH's excellent answer and wraps it up as an IEnumerable extension so that your code can deal in terms of None, One and Many rather than 0, 1 and 2.

public enum Multiplicity
{
    None,
    One,
    Many,
}

In a static class, e.g. EnumerableExtensions:

public static Multiplicity Multiplicity<TElement>(this IEnumerable<TElement> @this)
{
    switch (@this.Take(2).Count())
    {
        case 0: return General.Multiplicity.None;
        case 1: return General.Multiplicity.One;
        case 2: return General.Multiplicity.Many;
        default: throw new Exception("WTF‽");
    }
}

Tags:

C#

Linq