Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

c# - Linq GroupBy objects with an if else condition

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?

question from:https://stackoverflow.com/questions/65927196/linq-groupby-objects-with-an-if-else-condition

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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').


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...