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

后端 未结 4 900
庸人自扰
庸人自扰 2021-01-01 14:40

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.

4条回答
  •  旧时难觅i
    2021-01-01 14:58

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

    public static int CountUpTo(this IEnumerable 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;
    

提交回复
热议问题