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?
I wrote this extension method based off @Lee's response to the OP. Note, a default parameter was used (requiring C# 4.0). However, an overloaded method call in C# 3.0 would suffice.
Hope this wil help
Here is one way to do it:
The
GroupBy
groups the elements that are the same together, and theWhere
filters out those that only appear once, leaving you with only the duplicates.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.All mentioned solutions until now perform a GroupBy. Even if I only need the first Duplicate all elements of the collections are enumerated at least once.
The following extension function stops enumerating as soon as a duplicate has been found. It continues if a next duplicate is requested.
As always in LINQ there are two versions, one with IEqualityComparer and one without it.
Usage:
For all these linq statements the collection is only parsed until the requested items are found. The rest of the sequence is not interpreted.
IMHO that is an efficiency boost to consider.