Smith
Smith

Reputation: 5959

select duplicates in a list linq

i need to select duplicates from a list using linq and return list of arrays where each of the array contains the duplicates. for example if my list is

{2,2,3,13,4,4,15,5,7,8,9,12,13}

then i need returned

{2,2},{4,4}

the following code only returns a single value for each duplicate

int[] listOfItems = new[] {2,2,3,13,4,4,15,5,7,8,9,12,13};
var duplicates = listOfItems
    .GroupBy(i => i)
    .Where(g => g.Count() > 1)
    .Select(g => g.Key);
foreach (var d in duplicates)
    Console.WriteLine(d);

This produces the following:

4
2

Upvotes: 2

Views: 253

Answers (3)

Enigmativity
Enigmativity

Reputation: 117175

A simpler alternative is this:

listOfItems
    .ToLookup(x => x)
    .Where(x => x.Skip(1).Any());

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1504121

Well this is the problem:

    .Select(g => g.Key)

You're explicitly just selecting the key.

Remove that call, and you'll select all the groups instead - you'll get an IEnumerable<IGrouping<int, int>>. You'll need to change your output as well, of course. For example:

foreach (var group in duplicates)
{
    Console.WriteLine("{{{0}}}", group.Join(","));
}

EDIT: For a List<int[]> you just need:

var duplicates = listOfItems
    .GroupBy(i => i)
    .Where(g => g.Count() > 1)
    .Select(g => g.ToArray())
    .ToList();

Upvotes: 6

Rawling
Rawling

Reputation: 50214

Just get rid of the .Select(g => g.Key) line and you'll have, essentially, nested enumerables.

int[] listOfItems = new[] {2,2,3,13,4,4,15,5,7,8,9,12,13};
var duplicates = listOfItems
    .GroupBy(i => i)
    .Where(g => g.Count() > 1);

foreach (var g in duplicateGroups)
{
    foreach (var d in g)
    {
        Console.WriteLine(d); 
    }
    Console.WriteLine();
}

If you want a list of arrays, you'll want

var listOfArrays = duplicates.Select(g => g.ToArray()).ToList();

Similarly

var listOfLists = duplicates.Select(g => g.ToList()).ToList();
var arrayOfLists = duplicates.Select(g => g.ToArray()).ToList();
var arrayOfArrays = duplicates.Select(g => g.ToArray()).ToArray();

Upvotes: 2

Related Questions