【问题标题】:Lambda Expression to filter a list of list of items用于过滤项目列表的 Lambda 表达式
【发布时间】:2012-03-21 19:07:20
【问题描述】:

我有一个项目列表,我想知道是否有人可以帮助我使用 lambda 表达式来过滤此列表。

我的列表如下所示:

List<List<Item>> myList = ExtractList();

这是我的 Item 类的样子:

public class Item {
    public string Name {get;set;}
    public string Action {get;set;}
}

我想过滤此列表并仅获取项目名称 =“ABC”且项目操作 =“123”的项目列表列表。

感谢您的帮助

【问题讨论】:

  • 你应该澄清最后一句话,你想要一个包含 ABC/123 的列表吗?还是您想要包含 ABC/123 的项目列表?
  • 我想要一个包含 abc/123 的列表

标签: c# .net lambda


【解决方案1】:

简单:

myList.SelectMany(sublist => sublist)
    .Where(item => item.Name == "ABC" && item.Action == "123");

这将为您提供所有列表中的所有项目。

如果您想选择包含该项目的子列表:

myList.Where(sublist => sublist.Any(item => item.Name == "ABC" && item.Action == "123"));

最后,如果您想保留相同的结构,但只保留与过滤器匹配的项目:

var newList = myList.Select(sublist => sublist
                       .Where(item => item.Name == "ABC" && item.Action == "123")
                       .ToList()).ToList();

【讨论】:

  • 非常感谢!解决了我的问题。
【解决方案2】:

这里有一个列表,其中包含在列表中匹配 Name = "ABC" 和 Action = "123" 的一项。

var newList = myList.Where(l => 
             l.Exists(i => i.Name == "ABC" 
                    && i.Action == "123")).ToList();

如果您只需要符合条件的列表项列表,您可以这样做:

var newList = (from l in myList 
          where l.Exists(i => i.Name == "ABC" && i.Action == "123") 
          select l.Where(i => i.Name == "ABC" && i.Action == "123").ToList()).ToList();

要展平上面的列表(转换为简单列表而不是列表列表),您必须执行 foreach 循环:

List<Item> newList2 = new List<Item>();
foreach(var list in newList)
{
    newList2.AddRange(list);
}

【讨论】:

  • 不用foreach也可以展平:myList.SelectMany(l =&gt; l).ToList().
【解决方案3】:

我认为简单的 LINQ 语法最容易阅读:

var newList =
    // gets the list of items
    from listOfItems in myList
    // extracts the list of items
    from item in listOfItems
    // filters by criteria
    where item.Name == "ABC" && item.Action == "123"
    // flattens into a IEnumerable<Item>
    select item;

【讨论】:

    【解决方案4】:

    这可能有效;

    List<Item> Items = new List<Item>();
    
    myList.ForEach((item)=>
    {
       var items = item.Where(q=> q.Action == "123" && q.Name =="ABC");
       Items.AddRange(items);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多