How can I break List <T> into two lists, one of which contains all duplicate values, and the other contains the remainder?

I have a base class for the account (other properties removed for brevity):

public class Account
{
    public string Email { get; set; }
}

I have List<T>these accounts.

I can easily remove duplicates based on email address:

var uniques = list.GroupBy(x => x.Email).Select(x => x.First()).ToList();

A list called "uniques" now contains only one of each account based on the email address; any duplicates have been dropped.

I want to do something a little different and split the list into two.
One list will contain only "true" unique values, another list will contain duplicates of all .

For example, the following list of email messages in your account:

unique@email.com
dupe@email.com
dupe@email.com

:


unique@email.com


dupe@email.com
dupe@email.com

, , . .Except() , , . , , "" .

.NET Fiddle

?

, , LINQ. CodeReview, , .

+4
3
var duplicates = list.GroupBy(x => x) // or x.Property if you are grouping by some property.
                     .Where(g => g.Count() > 1)
                     .SelectMany(g => g);

var uniques = list.GroupBy(x => x) // or x.Property if you are grouping by some property.
                  .Where(g => g.Count() == 1)
                  .SelectMany(g => g);

, , Except:

var uniques = list.Except(duplicates);
// or
var duplicates = list.Except(uniques);
+3
var groups = list.GroupBy(x => x.Email)
                 .GroupBy(g => g.Count() == 1 ? 0 : 1)
                 .OrderBy(g => g.Key)
                 .Select(g => g.SelectMany(x => x))
                 .ToList();

groups[0] , group[1] .

+6

Another way to do this is to get uniques, and then for duplicates, just get items in the original list that are not in uniques.

IEnumerable<Account> uniques;
IEnumerable<Account> dupes;
dupes = list.Where(d => 
         !(uniques = list.GroupBy(x => x.Email)
                         .Where(g => g.Count() == 1)
                         .SelectMany(u => u))
         .Contains(d));
0
source

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


All Articles