Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ lambda expression, finding a child object where property is == X

Tags:

c#

lambda

linq

Need help with a LINQ lambda expression in C#.

So let me explain the structure of my object.

RootObject is a collection(custom class with multiple properties) that has many properties one of them is List<Item> items. Item contains a List<Round> Rounds. Round contains a EntryRID(this ID is unique) and name.

string = IDToFind = "111"; //The ID i want a Round object for 

So from my List of "items" i need to find the Round ID that matches a given ID(IDToFind). AKA i need to search every singe Item in "items" for a Round object with a ID matching IDToFind.

I've tired this expression:

Round playerRound = RootObject.Select(i => i.Items.Select(x => x.Rounds.Where(y => y.EntryRID == Int32.Parse(IDToFind))));

but its not return any kind of object, its returning:

System.Linq.Enumerable+WhereSelectListIterator`2[Leaderboards,System.Collections.Generic.IEnumerable`1[System.Collections.Generic.IEnumerable`1[Round]]]
like image 337
user2408952 Avatar asked Dec 13 '25 17:12

user2408952


1 Answers

It sounds like you want something like:

// Parse the target ID *once* rather than all the time...
var targetId = int.Parse(IDToFind);
var playerRound = RootObject.SelectMany(i => i.Items)
                            .SelectMany(x => x.Rounds)
                            .Where(round => round.EntryRID == targetId)
                            .First();

That will return first matching Round, or throw an exception if there aren't any. You could use FirstOrDefault which will return null if there are no matching objects, or perhaps Single() which will make sure there's exactly one result.

As a query expression, you can write the above as:

var targetId = int.Parse(IDToFind);
var playerRound = (from foo in RootObject // You haven't told us this type
                   from item in foo.Items
                   from round in item.Rounds
                   where round.EntryRID == targetId
                   select round).First();
like image 171
Jon Skeet Avatar answered Dec 15 '25 06:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!