[英]How can I find object in List with Linq?
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的对象?
If you are trying to find an object in collectionMyObject
which 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 SelectMany
might be helpful: 如果您尝试查找ID为2的内部项,则使用SelectMany
进行此查询可能会有所帮助:
MyObject myObject1 = collectionMyObject.Where(o => o.Items != null).SelectMany(o => o.Items).FirstOrDefault(io => io.Id == 2);
var item = collectionMyObject.FirstOrDefault(x => x.Id == 2);
编辑:我误解了这个问题所以安德烈的答案看起来比我的好。
简单:
var obj = collectionMyObject.FirstOrDefault(o => o.Id == 2);
Another way may be: 另一种方式可能是:
(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()
. 如果想要单个条目,则用FirstOrDefault()
替换ToList()
FirstOrDefault()
。
Hope it helps. 希望能帮助到你。
Using the Where
keyword and a lambda like so: 使用Where
关键字和lambda如下:
MyObject result = collectionMyObject.Where(x => x.Id == 2).FirstOrDefault()
Or, to find in the Items
sub-collection simply do: 或者,要在Items
子集合中查找,只需执行以下操作:
MyObject result = collectionMyObject.Where(x => x.Item.Id == 2).FirstOrDefault()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.