I have a object:
public class MyObject
{
public int Id { get; set; }
public List<MyObject> Items { get; set; }
}
And I have list of 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 ?
If you are trying to find an object in collectionMyObject
which has item with id 2, then this should work:
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:
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);
EDIT: I misread the question so Andrei's answer looks better than mine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With