C# 在 linq 的 where 方法中使用多个条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2281083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:00:04  来源:igfitidea点击:

Using more than one condition in linq's where method

c#

提问by GurdeepS

I have a line of code using where:

我有一行代码使用 where:

codebase.Methods.Where(x => x.Body.Scopes.Count > 5);

How can I insert more than one condition? So I can say x => predicate && y => predicate?

如何插入多个条件?所以我可以说x => predicate && y => predicate

Thanks

谢谢

采纳答案by LukeH

You can roll your separate conditions into a single predicate if you like:

如果您愿意,可以将单独的条件合并为单个谓词:

codebase.Methods.Where(x => (x.Body.Scopes.Count > 5) && (x.Foo == "test"));

Or you can use a separate Wherecall for each condition:

或者您可以Where对每个条件使用单独的调用:

codebase.Methods.Where(x => x.Body.Scopes.Count > 5)
                .Where(x => x.Foo == "test");

回答by Jeeva Subburaj

like this..

像这样..

codebase.Methods.Where(x => x.Body.Scopes.Count > 5 && x.Body.Scopes.Count < 10);

回答by TheSoftwareJedi

What would "y" represent?

“y”代表什么?

You can just use a standard && condition. No need for a "y":

您可以只使用标准 && 条件。不需要“y”:

codebase.Methods.Where(x => x.Body.Scopes.Count > 5 && x.Body.SomethingElse < 14);

回答by Rex M

In your example, where does ycome from? The Wheremethod takes a lambda with a single input parameter, which represents a single instance of the sequence you're operating against.

在你的例子中,y从哪里来?该Where方法采用带有单个输入参数的 lambda,该参数表示您正在操作的序列的单个实例。

You can, of course, have multiple conditions against x:

当然,您可以针对x以下条件设置多个条件:

Where(x => x.Foo > 5 && x.Bar < 3)

回答by Klaus Byskov Pedersen

I don't get it. What can you not do?

我不明白。你不能做什么?

codebase.Methods.Where(x => x.Head.IsHairy && x.Body != null && x.Body.Scopes.Count > 5); 

回答by Amgad Fahmi

no you can't define 2 delegates in the same where but you can build after each other or put both on same condition like this

不,你不能在同一个地方定义 2 个委托,但你可以互相构建或像这样将两者放在相同的条件下

 var result = codebase.Methods.Where(x => x.Body.Scopes.Count > 5 && x.Body.Scopes.name == "" );

or 

 var result = codebase.Methods.Where(x => x.Body.Scopes.Count > 5 )
        .where( y=> y.Body.Scopes.name == '' );

or 

 var result = codebase.Methods.Where(x => x.Body.Scopes.Count > 5  )
.Union( codebase.Methods.Where(y => y.Body.Scopes.name == ''  ) );

回答by Majosty D

codebase.Methods.Where(x => x.Body.Scopes.Count > 5).Where(x => x.Body.Scopes.TypeName == "Scopes").Where(x => x.Body.Scopes.Level == LEVEL_HIGH);