How to get duplicate items from a list using LINQ? [duplicate]
I'm having a List<string>
like:
List<String> list = new List<String>{"6","1","2","4","6","5","1"};
I need to get the duplicate items in the list into a new list. Now I'm using a nested for
loop to do this.
The resulting list
will contain {"6","1"}
.
Is there any idea to do this using LINQ or lambda expressions?
Solution 1:
var duplicates = lst.GroupBy(s => s)
.SelectMany(grp => grp.Skip(1));
Note that this will return all duplicates, so if you only want to know which items are duplicated in the source list, you could apply Distinct
to the resulting sequence or use the solution given by Mark Byers.
Solution 2:
Here is one way to do it:
List<String> duplicates = lst.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(g => g.Key)
.ToList();
The GroupBy
groups the elements that are the same together, and the Where
filters out those that only appear once, leaving you with only the duplicates.