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]]]
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();
See more on this question at Stackoverflow