Is there a better way of calling LINQ Any + NOT All?

后端 未结 8 943
走了就别回头了
走了就别回头了 2021-02-18 14:46

I need to check if a sequence has any items satisfying some condition but at the same time NOT all items satisfying the same condition.

For example, for a sequence of 10

8条回答
  •  长发绾君心
    2021-02-18 15:14

    You could define your own extension method. This version is more verbose, but still readable, and it only enumerates the IEnumerable once:

    bool AnyButNotAll(this IEnumerable sequence, Func predicate)
    {
        bool seenTrue = false;
        bool seenFalse = false;
    
        foreach (ItemT item in sequence)
        {
            bool predResult = predicate(item);
            if (predResult)
                seenTrue = true;
            if (!predResult)
                seenFalse = true;
    
            if (seenTrue && seenFalse)
                return true;
        }
    
        return false;
    }
    

    Much shorter, but enumerates the IEnumerable twice:

    bool AnyButNotAll(this IEnumerable sequence, Func predicate)
    {
        return sequence.Any(predicate) && !sequence.All(predicate);
    }
    

提交回复
热议问题