9

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 ?

5 Answers 5

18

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer! I'm a little corrected query and it works Where(s => s.Items != null).SelectMany(o => o.Items).FirstOrDefault(io => io.Id == 2);
9
var item = collectionMyObject.FirstOrDefault(x => x.Id == 2);

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

1 Comment

Thanks for the answer! I probably asked the wrong question I had in mind, the search for Items too.
4

Simple:

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

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.