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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With