【问题标题】:LINQ: Filtering items List by some condition and do something with item by conditionLINQ:按某些条件过滤项目列表并按条件对项目做一些事情
【发布时间】:2018-08-30 17:56:01
【问题描述】:

假设我有users,即List<User>,并且User 类有TypeAge 属性。 我想按某些条件过滤该用户列表,并根据条件对每个项目执行一些操作。让这个列表有 10 个用户,其中一些是 "complex" 类型,其中一些是 "simple"。我希望我的最终列表是年龄在 30 岁以上的用户,如果用户类型是“复杂”,则在上面做一些事情,然后将其添加到最终列表中。应该是这样的:

var users= users.Where(u => u.Age > 30 
and if u.Type = "complex" ? u = doSomething(u)).ToList();

如果doSomething(u) 返回null,则跳过当前“u”以添加到列表中。

它一半是正确的代码,一半是伪代码,因为我不知道如何将if u.Type = "complex" ? u = doSomething(u) 部分放入 LINQ 表达式中。怎么办?

编辑:如果我希望最终 lsit 用户年龄 > 30 或 Type = "complex" 的用户(和 doSomething())在复杂用户上,该怎么做?

【问题讨论】:

  • 所以你想要Age > 30 OR users with Type = "complex" Age > 30 AND users with Type = "complex"

标签: c# .net linq filtering


【解决方案1】:

和查询

var andList = users.Where(u => u.Age > 30 && (u.Type == "complex" && doSomething(u) != null)).ToList();

或查询

var orList = users.Where(u => u.Age > 30 || (u.Type == "complex" && doSomething(u) != null)).ToList();

【讨论】:

    【解决方案2】:

    我会做如下事情:

    users.Where(u => u.Age > 30).Select((u) =>
    {
        if (u.Type == "complex")
        {
            // Do something
        }
    
        return u;
    }).ToList();
    

    选择所有年龄 > 30 的用户,然后根据 type 属性更改结果。

    编辑: 对于您的编辑问题,只需将条件添加到 where :

    [...].Where(u => u.Age > 30 || u.Type == "complex")[...]
    

    【讨论】:

      【解决方案3】:

      嗯,我想出了一些病态的变种......

      public bool DoSomething()
      {
          // Do anything
          return true;
      }    
      
      var v = users.Where(x => x!= null && x.Age > 30 && x.Type == "Complex" && x.DoSomething() == true).ToList();
      

      供您编辑:

      var v = users.Where(x => x!= null && (x.Age > 30 || x.Type == "Complex") && x.DoSomething() == true).ToList();
      

      【讨论】:

        【解决方案4】:
        var users = users.Where(u => u.Age > 30) // common filter
                         .Select(u => u.Type == "complex" ? doSomething(u) : u) //select user or transformed
                         .Where(u => u != null) //not null only
                         .ToList();
        

        【讨论】:

        • 您可以更进一步,将条件“type == complex”隐藏在函数中,并为函数命名以使其更具可读性。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-09
        • 2022-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多