Alexandr
Alexandr

Reputation: 1901

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 ?

Upvotes: 9

Views: 37825

Answers (5)

Andrei
Andrei

Reputation: 56688

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);

Upvotes: 18

Sandy
Sandy

Reputation: 11687

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().

Hope it helps.

Upvotes: 1

orel
orel

Reputation: 1469

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

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

Upvotes: 9

DGibbs
DGibbs

Reputation: 14608

Simple:

var obj = collectionMyObject.FirstOrDefault(o => o.Id == 2);

Upvotes: 4

Belogix
Belogix

Reputation: 8147

Using the Where keyword and a lambda like so:

MyObject result = collectionMyObject.Where(x => x.Id == 2).FirstOrDefault()

Or, to find in the Items sub-collection simply do:

MyObject result = collectionMyObject.Where(x => x.Item.Id == 2).FirstOrDefault()

Upvotes: 0

Related Questions