Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq GroupBy objects with an if else condition

Tags:

c#

linq

I'm new to c# linq and struggling with something. I have a list and want to gather from it specific info as in the following example:

Lets say I have the following list of kidsEat objects:

{NAME=joseph, FOOD=banana, EATEN=true}
 
{NAME=joseph, FOOD=apple, EATEN=false}

{NAME=billy, FOOD=banana, EATEN=false}

{NAME=billy, FOOD=apple, EATEN=false}

From this list, I want to know for each of the boys if he has eaten anything or not.

If he did eat something, it will take the object that says he ate.

If he did not eat, it will take one random object where he didn't eat.

So, this example should return list of following 2 objects:

{NAME=joseph, FOOD=banana, EATEN=true}

{NAME=billy, FOOD=banana, EATEN=false}     //banana could be switched to apple, it doesn't matter

So. I thought of something like:

KidsList.GroupBy(kid=>kid.NAME).Where().Select(kid=>kid.First())

But I don't know what to put in the where clause, because its like going over all rows, then finding if one of them is true, and if so putting "true" else putting false. It feels like it needs some if else inside the LINQ query.

Any help?

like image 452
E.Mich Avatar asked Jan 26 '26 00:01

E.Mich


2 Answers

Select either first 'eaten' record, or first 'not eaten' record if there are no 'eaten' records

KidsList.GroupBy(k => k.NAME)
  .Select(g => g.FirstOrDefault(k => k.EATEN) ?? g.First())

Explanation: If there are no records matching k => k.EATEN predicate then FirstOrDefault will return the default value, which is null. In this case null-coalescing operator ?? will evaluate the right-hand operand and return the First record (which obviously will be 'not eaten').

like image 72
Sergey Berezovskiy Avatar answered Jan 28 '26 13:01

Sergey Berezovskiy


You could order the group elements by EATEN and then pick the first element:

var ans = src.GroupBy(e => e.NAME)
             .Select(eg => eg.OrderByDescending(e => e.EATEN).First());
like image 36
NetMage Avatar answered Jan 28 '26 14:01

NetMage