是否有&QUOT等效;无()"在LINQ?QUOT、LINQ

2023-09-03 06:11:45 作者:心裏有座墳,葬著未亡人

我已经运行到哪里,我觉得我缺乏这effectivelly检查,如果没有匹配的指定predicate集合中的一个LINQ扩展方法的情况。有任何所有,但如果我例如使用下面的code:

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:

如果(Objects.All(U => u.Distance< = 0))

此,如果集合中的所有对象都小于或等于0码远返回true。

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

如果(Objects.Any(U => u.Distance< = 0))

这如果是0或更小码的距离是从我的收藏中至少有一个对象返回true。

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

到目前为止好,这两个方法的意义和语法他们有道理了。现在,如果我要检查是否存在与0或更小的距离没有对象,我有反转所有法里面的predicate到> = 0 而不是<!= 0 或拨打所有(),在某些情况下会导致非常糟糕可读code。

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.

有没有一种方法,有效地做 Col​​lection.None(U =&GT; u.Distance&LT; = 0)来检查是否有集合中没有对象,小于等于0码的距离?它的语法糖超过了实际的问题,但我只是它缺少的感觉。

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.

推荐答案

是一样的!不限 ,所以如下,你可以定义自己的扩展方法:

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