Lambda Expression过滤项目列表 [英] Lambda Expression to filter a list of list of items
本文介绍了Lambda Expression过滤项目列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个项目列表,我想知道是否有人可以用lambda表达式来帮助我过滤该列表.
I have a a list of list of items and I was wondering if someone could help me with a lambda expression to filter this list.
这是我的列表的样子:
List<List<Item>> myList = ExtractList();
这是我的Item类的样子:
Here's what my Item class looks like:
public class Item {
public string Name {get;set;}
public string Action {get;set;}
}
我想过滤此列表,并仅获取其中项目名称"为"ABC"且项目"Action"为"123"的项目列表.
I would like to filter this list and get only those List of List of Items where the Item Name = "ABC" and item Action = "123".
感谢您的帮助
推荐答案
简单:
myList.SelectMany(sublist => sublist)
.Where(item => item.Name == "ABC" && item.Action == "123");
这将为您提供所有列表中的所有项目.
This gives you all the items inside all the lists.
如果要选择包含该项目的子列表,则:
If you want to select sublists that contain the item instead:
myList.Where(sublist => sublist.Any(item => item.Name == "ABC" && item.Action == "123"));
最后,如果您想保留相同的结构,但只保留与过滤器匹配的项目:
And lastly if you want to preserve the same structure but only keep the items that match the filter:
var newList = myList.Select(sublist => sublist
.Where(item => item.Name == "ABC" && item.Action == "123")
.ToList()).ToList();
这篇关于Lambda Expression过滤项目列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文