我有一個目標:如何在Linq中查找列表中的對象?
public class MyObject
{
public int Id { get; set; }
public List<MyObject> Items { get; set; }
}
而且我的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
});
我怎樣才能找到ID = 2的對象在collectionMyObject使用LINQ?
感謝您的回答!我有點糾正查詢,它的工作原理Where(s => s.Items!= null).SelectMany(o => o.Items).FirstOrDefault(io => io.Id == 2); – Alexandr
@Alexandr,更新了考慮到空值的答案。 – Andrei
好的,謝謝! :) – Alexandr