C# Lambda 表达式中的多个 Where 子句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1748047/
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-06 20:27:37  来源:igfitidea点击:

Multiple Where clauses in Lambda expressions

c#.netlambda

提问by ashwnacharya

I have a simple lambda expression that goes something like this:

我有一个简单的 lambda 表达式,它是这样的:

x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty)

Now, if I want to add one more where clause to the expression, say, l.InternalName != String.Emptythen what would the expression be?

现在,如果我想在表达式中l.InternalName != String.Empty再添加一个 where 子句,那么表达式会是什么?

采纳答案by Rubens Farias

Can be

x => x.Lists.Include(l => l.Title)
     .Where(l => l.Title != String.Empty && l.InternalName != String.Empty)

or

或者

x => x.Lists.Include(l => l.Title)
     .Where(l => l.Title != String.Empty)
     .Where(l => l.InternalName != String.Empty)

When you are looking at Whereimplementation, you can see it accepts a Func(T, bool); that means:

当您查看Where实现时,您可以看到它接受一个Func(T, bool); 这意味着:

  • Tis your IEnumerable type
  • boolmeans it needs to return a boolean value
  • T是您的 IEnumerable 类型
  • bool意味着它需要返回一个布尔值

So, when you do

所以,当你做

.Where(l => l.InternalName != String.Empty)
//     ^                   ^---------- boolean part
//     |------------------------------ "T" part

回答by Winston Smith

x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty).Where(l => l.Internal NAme != String.Empty)

or

或者

x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty && l.Internal NAme != String.Empty)

回答by Joey

Maybe

也许

x=> x.Lists.Include(l => l.Title)
    .Where(l => l.Title != string.Empty)
    .Where(l => l.InternalName != string.Empty)

?

?

You can probably also put it in the same where clause:

你也可以把它放在同一个 where 子句中:

x=> x.Lists.Include(l => l.Title)
    .Where(l => l.Title != string.Empty && l.InternalName != string.Empty)

回答by Joey

You can include it in the same where statement with the && operator...

您可以使用 && 运算符将其包含在相同的 where 语句中...

x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty 
    && l.InternalName != String.Empty)

You can use any of the comparison operators (think of it like doing an if statement) such as...

您可以使用任何比较运算符(将其视为执行 if 语句),例如...

List<Int32> nums = new List<int>();

nums.Add(3);
nums.Add(10);
nums.Add(5);

var results = nums.Where(x => x == 3 || x == 10);

...would bring back 3 and 10.

...会带回 3 和 10。

回答by AakashM

The lambda you pass to Wherecan include any normal C# code, for example the &&operator:

您传递给的 lambdaWhere可以包含任何普通的 C# 代码,例如&&运算符:

.Where(l => l.Title != string.Empty && l.InternalName != string.Empty)