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
Well this is the problem:
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:EDIT: For a
List<int[]>you just need: