GetOffMyLawn
GetOffMyLawn

Reputation: 11

Linq group objects by unique values and make two lists

I have an array of objects with property Number inside them. I need to group them by values i.e. objects contain those sample values:

1 2 3 3 3 4 5 6 6 6 7 7

I have to group them like this:

listOfUniqe = {1,2,4,5}
listOfDuplicates1 = {3,3,3}
listOfDuplicates2 = {6,6,6}
listOfDuplicates3 = {7,7}
...

I tried to use distinct, with First(). But this distincts me first occurences and remove duplicates. I want to erase also first occurence of object if it had duplicates and move them to another list.

List<Reports> distinct = new List<Reports>;
distinct = ArrayOfObjects.GroupBy(p => p.Number).Select(g => g.First()).ToList();

Any ideas how I could do this?

Upvotes: 1

Views: 3612

Answers (2)

Guffa
Guffa

Reputation: 700152

First group the items:

var groups = values.GroupBy(p => p.Number).ToList();

The unique ones are the ones with a group count of one:

var unique = groups.Where(g => g.Count() == 1).Select(g => g.Single()).ToList();

The ones with duplicates are the other ones:

var nonUnique = groups.Where(g => g.Count() > 1).ToList();

Upvotes: 4

MarcinJuraszek
MarcinJuraszek

Reputation: 125610

To get groups with just one element use that:

distinct = ArrayOfObjects.GroupBy(p => p.Number)
                         .Where(g => g.Count() == 1)
                         .ToList();

And to get list of groups with more elements use that:

nonDistinct = ArrayOfObjects.GroupBy(p => p.Number)
                            .Where(g => g.Count() > 1)
                            .Select(g => g.ToList())
                            .ToList();

Upvotes: 5

Related Questions