❔ Help with linq query
I have a list of cutomers that gets grouped according to their addresss and data property. I would like to select the first group where the data is equal to Klepto or some other thing. From the code I have I am expecting to retrieve customer 1 and customer 3 as they both have Klepto as their data.
Here are my customers, I add these to CustList later on.
The expected result is cust 1 and 3 but its not what I get. the attached image shows what I get.
3 Replies
.Select(x => x.FirstOrDefault(y => y.SomeData.Equals("Klepto"))).ToList();
You are projecting each group to their first element
You need to filter instead:
Since LINQ has a ton of utility overloads, you can also add a predicate to First
:
.First(x => x.Any(y => y.SomeData.Equals("Klepto"))).ToList();
Essentially the same dealThank you very much. I was wondering why I keep getting nulls along with customer 1 but I never got customer 3. The query you provided works very well!
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.