Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting specific distinct record to a list using linq

Tags:

c#

linq

I've been using this:

return myListOfContacts.DistinctBy(e => e.Id).Where(e => e.CompanyId == companyId).ToList();

Which returns a distinct list, as requested. The problem is, when the records are duplicate, the returned record is the first on the list.

For example, if in my contacts I have these:

[Id - ContactId - Name - FlagIWantThisOne]

1 - 99 - John - true
2 - 56 - Mike - false
2 - 56 - Mike - true
3 - 13 - Dave - false

It returns 3 records:

John, Mike and Dave.

But the "Mike" record I want is the one with the flag as true.

In all, if a record is duplicate, the list should return the one with the flag set to true and ignore the others.

I got the distinctBy there, but it is returning the first one it finds on the list.

like image 228
chiapa Avatar asked Feb 08 '23 22:02

chiapa


1 Answers

You might try:

myListOfContacts.GroupBy(e => e.Id)
                .Select(g => g.OrderByDescending(r => r.FlagIwantThisOne).First())
                .ToList();

The logic is:

Group by Id. Then, sort through group descending (true > false), and take the first one from each group.

like image 89
Rob Avatar answered Feb 16 '23 04:02

Rob