How to ask "Is there exactly one element satisfying condition" in LINQ?

You could use this extension method, which I think should have been included in the standard extension methods for linq:

public static int CountUpTo<T>(this IEnumerable<T> sequence, int maxCount) {
    if (sequence == null) throw new ArgumentNullException("sequence");
    if (maxCount < 0) throw new ArgumentOutOfRangeException("maxCount");

    var count = 0;
    var enumerator = sequence.GetEnumerator();
    while (count < maxCount && enumerator.MoveNext())
        count += 1;
    return count;
}

Used like so:

return sequence.CountUpTo(2) == 1;

You could do:

bool onlyOne = source.Where(/*condition*/).Take(2).Count() == 1

Which will prevent count from enumerating a large sequence unnecessarily in the event of multiple matches.


The simplest way is to just use Count. Single won't work for you, because it throws an exception if there isn't just that single element.

LBushkin suggests (in the comments) to use SequenceEqual to compare a sequence with another one. You could use that by skipping the first element with Skip(1), and comparing the resulting sequence to an empty sequence such as what you can get from Empty

Tags:

C#

.Net

Linq