C# 如何使用 Linq 在 List 中找到对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17401295/
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
How can I find object in List with Linq?
提问by Alexandr
I have a object:
我有一个对象:
public class MyObject
{
public int Id { get; set; }
public List<MyObject> Items { get; set; }
}
And I have list of MyObject:
我有 MyObject 列表:
List<MyObject> collection = new List<MyObject>();
collection.Add(new MyObject()
{
Id = 1,
Items = null
});
collection.Add(new MyObject()
{
Id = 2,
Items = null
});
collection.Add(new MyObject()
{
Id = 3,
Items = null
});
List<MyObject> collectionMyObject = new List<MyObject>();
collectionMyObject.Add(new MyObject()
{
Id = 4,
Items = collection
});
collectionMyObject.Add(new MyObject()
{
Id = 5,
Items = null
});
How can I find object with Id = 2 in collectionMyObject with Linq ?
如何使用 Linq 在 collectionMyObject 中找到 Id = 2 的对象?
采纳答案by Andrei
If you are trying to find an object in collectionMyObjectwhich has item with id 2, then this should work:
如果您正在尝试查找collectionMyObject包含 id 为 2 的项目的对象,那么这应该可以工作:
MyObject myObject = collectionMyObject.FirstOrDefault(o => o.Items != null && o.Items.Any(io => io.Id == 2));
And if you are try to find an inner item with id 2, then this query with SelectManymight be helpful:
如果您尝试查找 id 为 2 的内部项目,那么此查询SelectMany可能会有所帮助:
MyObject myObject1 = collectionMyObject.Where(o => o.Items != null).SelectMany(o => o.Items).FirstOrDefault(io => io.Id == 2);
回答by Belogix
Using the Wherekeyword and a lambda like so:
Where像这样使用关键字和 lambda:
MyObject result = collectionMyObject.Where(x => x.Id == 2).FirstOrDefault()
Or, to find in the Itemssub-collection simply do:
或者,要在Items子集合中查找,只需执行以下操作:
MyObject result = collectionMyObject.Where(x => x.Item.Id == 2).FirstOrDefault()
回答by DGibbs
Simple:
简单的:
var obj = collectionMyObject.FirstOrDefault(o => o.Id == 2);
回答by orel
var item = collectionMyObject.FirstOrDefault(x => x.Id == 2);
EDIT: I misread the question so Andrei's answer looks better than mine.
编辑:我误读了这个问题,所以安德烈的回答看起来比我的好。
回答by Sandy
Another way may be:
另一种方式可能是:
(from c in collection where c.Id == 2 select c).ToList;
(from c in collection where c.Id == 2 select c).ToList;
It should give a list in return. If want a single entry, then replace ToList()with FirstOrDefault().
它应该给出一个列表作为回报。如果想要单个条目,则替换ToList()为FirstOrDefault().
Hope it helps.
希望能帮助到你。

