【问题标题】:Multiple Where clauses in Lambda expressionsLambda 表达式中的多个 Where 子句
【发布时间】:2010-12-17 09:50:48
【问题描述】:

我有一个简单的 lambda 表达式,如下所示:

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

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

【问题讨论】:

  • 这有点跑题了,但是字符串类有一个方法 String.IsNullOrEmpty,您可以使用它而不是与 String.Empty 进行比较

标签: c# .net lambda


【解决方案1】:

可以

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

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

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

  • T 是你的 IEnumerable 类型
  • bool 表示需要返回一个布尔值

所以,当你这样做时

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      您可以使用任何比较运算符(将其想象为执行 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);
      

      ...会带回 3 和 10。

      【讨论】:

        【解决方案4】:

        也许

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

        ?

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

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

        【讨论】:

          【解决方案5】:
          x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty).Where(l => l.Internal NAme != String.Empty)
          

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-05-29
            • 2021-09-04
            • 2014-05-19
            • 1970-01-01
            • 2017-10-10
            • 1970-01-01
            相关资源
            最近更新 更多