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

后端 未结 8 946
走了就别回头了
走了就别回头了 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:26

    That is likely a fairly optimal solution if the source is a database. This extension method might be better depending on your source (I think, I just threw it together -- likely many many errors, consider it more pseudo code). The benefit here is it only enumerates once and does a short-circuit as soon as it has read enough to determine the outcome:

    static bool SomeButNotAll<TSource>(this IEnumerable<TSource> source,
                                       Func<TSource, bool> predicate)
    {
       using(var iter=source.GetEnumerator())
       {
         if (iter.MoveNext())
         {
           bool initialValue=predicate(iter.Current);
           while (iter.MoveNext())
             if (predicate(iter.Current)!=initialValue)
               return true;
         }
       }     
       return false; /* All */
    }
    
    0 讨论(0)
  • 2021-02-18 15:26

    You could try this:

    var result = mySequence.Select(item => item.SomeStatus == SomeConst)
                          .Distinct().Count() > 1 ? false : true;
    

    Basically I select true or false for each value, get distinct to only get one of each, then count those.

    0 讨论(0)
提交回复
热议问题