C# 用于过滤项目列表的 Lambda 表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9811219/
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
Lambda Expression to filter a list of list of items
提问by zSynopsis
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.
我有一个项目列表,我想知道是否有人可以帮助我使用 lambda 表达式来过滤此列表。
Here's what my list looks like:
这是我的清单:
List<List<Item>> myList = ExtractList();
Here's what my Item class looks like:
这是我的 Item 类的样子:
public class Item {
public string Name {get;set;}
public string Action {get;set;}
}
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".
我想过滤此列表并仅获取项目名称 =“ABC”和项目操作 =“123”的项目列表列表。
Thanks for any help
谢谢你的帮助
采纳答案by Roman Starkov
Simple:
简单的:
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();
回答by Diego
Here's one that gets you lists that contain at list one item matching Name = "ABC" and Action = "123".
这是一个可以让您列出包含匹配 Name = "ABC" 和 Action = "123" 的项目的列表。
var newList = myList.Where(l =>
l.Exists(i => i.Name == "ABC"
&& i.Action == "123")).ToList();
If you need only a list of list items that match the condition, you can do:
如果您只需要符合条件的列表项列表,您可以执行以下操作:
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();
To flatten the list above (convert into a simple list instead of lists of lists), you'll have to do a foreachloop:
要展平上面的列表(转换为简单列表而不是列表列表),您必须执行一个foreach循环:
List<Item> newList2 = new List<Item>();
foreach(var list in newList)
{
newList2.AddRange(list);
}
回答by daryal
This may work;
这可能有效;
List<Item> Items = new List<Item>();
myList.ForEach((item)=>
{
var items = item.Where(q=> q.Action == "123" && q.Name =="ABC");
Items.AddRange(items);
});
回答by code4life
I think the simple LINQ syntax is the easiest to read:
我认为简单的 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;

