Is there an equivalent of “None()” in LINQ?

前端 未结 3 1312
天涯浪人
天涯浪人 2021-02-06 23:19

I\'ve been running into situations where I feel I\'m lacking a LINQ extension method which effectivelly checks if there is no match of the specified predicate in a collection. T

相关标签:
3条回答
  • 2021-02-06 23:40

    You can write your own Extension Method:

    public static bool None(this IEnumerable<T> collection, Func<T, bool> predicate)
    {
      return collection.All(p=>predicate(p)==false);
    }
    

    Or on IQueryable<T> as well

    public static bool None(this IQueryable<T> collection, Expression<Func<TSource, bool>> predicate)
    {
      return collection.All(p=> predicate(p)==false);
    }
    
    0 讨论(0)
  • 2021-02-06 23:43

    Even shorter version

    static class LinqExtensions
    {
        public static bool None<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => !source.Any(predicate);
    }
    
    0 讨论(0)
  • 2021-02-06 23:54

    None is the same as !Any, so you could define your own extension method as follows:

    public static class EnumerableExtensions
    {
        public static bool None<TSource>(this IEnumerable<TSource> source,
                                         Func<TSource, bool> predicate)
        {
            return !source.Any(predicate);
        }
    }
    
    0 讨论(0)
提交回复
热议问题