否定`.Where()`LINQ表达式

Per*_*nce 5 c# linq lambda

我知道您可以执行以下操作:

enumerable.Where(MethodGroup).DoSomething();
Run Code Online (Sandbox Code Playgroud)

并且这实现了同样的事情:

enumerable.Where(x => MyMethod(x)).DoSomething();
Run Code Online (Sandbox Code Playgroud)

但是,我希望实现与此相反并选择方法返回false的项目.很明显,第二种情况如何做到这一点:

enumerable.Where(x => !MyMethod(x)).DoSomething();
Run Code Online (Sandbox Code Playgroud)

然而,对于第一种情况,情况并非如此,因为您无法将!运算符应用于a MethodGroup.有可能以类似的方式实现这种" .WhereNot"效果,MethodGroups还是我必须自己滚动(或使用lambdas)?

vyr*_*yrp 6

您可以创建一个辅助方法:

public static Func<T, bool> Not<T>(Func<T, bool> method) 
{
    return x => !method(x);
} 
Run Code Online (Sandbox Code Playgroud)

然后用法将与您想要的非常相似:

someEnumerable.Where(Not(MyMethod)).DoSomething();
Run Code Online (Sandbox Code Playgroud)

  • 或者你可以像`public static IEnumerable <T> WhereNot <T>(这个IEnumerable <T> enumerable,Func <T,bool>谓词){return enumerable.Where(e =>!predicate(e))一样使用所有东西; }` (3认同)

Nik*_*wal 6

LINQ 中提供的方法集没有直接的方法可以做到这一点。即使你以某种方式实现了这一目标,它也不会是一个有效的目标。

正如你所设想的,需要像这样制作一个新的

public static IEnumerable<TSource> WhereNot<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
    return source.Where(x => !predicate(x));
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它

var inverseResult = lst.WhereNot(MyMethod);
Run Code Online (Sandbox Code Playgroud)