Getting a single entry to a list using linq

I used this:

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

Returns a separate list as requested. The problem is that when the records are duplicated, the returned record is the first in the list.

For example, if in my contacts I have:

[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 record "Mike" I want is a flag with the flag as true.

In general, if the entry is repeated, the list should return the one with the flag set to true, and ignore the rest.

I got distinctBythere, but it returns the first one that it finds in the list.

+4
source share
4 answers

You may try:

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

The logic is this:

. (true > false) .

+4

. , where , :

return myListOfContacts.Where(e => e.CompanyId == companyId)
                       .OrderBy(e => e.Flag)
                       .DistinctBy(e => e.Id)
                       .ToList();
+2

, O (N * log (N)), O (N) :

return myListOfContacts
    .Where(e => e.CompanyId == companyId)
    .GroupBy(e => e.Id, (key, elements) =>
        elements.FirstOrDefault(e => e.FlagIWantThisOne) ?? elements.First())                   .OrderBy(e => e.Flag)
    .ToList();

, , , true, . "

+2

:

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

, .

0

Source: https://habr.com/ru/post/1625807/


All Articles