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

倖福魔咒の 提交于 2020-08-01 09:20:49

问题


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. There is Any and All, but if I for instance use the following code:

if (Objects.All(u => u.Distance <= 0))

This returns true if all the objects in the collection are 0 or less yards away.

if (Objects.Any(u => u.Distance <= 0))

This returns true if there is at least one object in the collection which is 0 or less yards away from me.

So far so good, both those methods make sense and the syntax for them makes sense too. Now, if I want to check if there is no object with 0 or less distance, I'd have to invert the predicate inside the All method to >= 0 instead of <= 0 or call !All(), which in some cases results in very poorly readable code.

Is there no method which effectively does Collection.None(u => u.Distance <= 0) to check if there is no object in the collection which is 0 or less yards away? It's syntactic sugar more than an actual problem, but I just have the feeling it's missing.


回答1:


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);
    }
}



回答2:


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);
}



回答3:


Even shorter version

static class LinqExtensions
{
    public static bool None<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => !source.Any(predicate);
}


来源:https://stackoverflow.com/questions/19338122/is-there-an-equivalent-of-none-in-linq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!