Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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 ?

like image 528
Alexandr Avatar asked Jul 01 '13 09:07

Alexandr


2 Answers

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);
like image 152
Andrei Avatar answered Oct 05 '22 23:10

Andrei


var item = collectionMyObject.FirstOrDefault(x => x.Id == 2);

EDIT: I misread the question so Andrei's answer looks better than mine.

like image 25
orel Avatar answered Oct 06 '22 00:10

orel