7

I have a customers List(of String) on which I am trying to find the duplicate customers.

If Not customers.Count = customers.Distinct.ToList.Count Then
     customers = customers.Except(customers.Distinct.ToList)
End If

But I get the following exception:

InvalidCastException
Unable to cast object of type '<ExceptIterator>d__99`1[System.String]' to type

'System.Collections.Generic.List`1[System.String]'.

Is this the right way to find duplicates in a list?

2 Answers 2

11
customers = customers.GroupBy(Function(m) m) _
                 .Where(Function(g) g.Count() > 1) _
                 .Select(Function(g) g.Key).ToList
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but Except seems not removing the duplicates. Count of customers is 0 after this step. (customers.count = 581, customers.Distinct.ToList.count = 575)
@emaillenin yes, cause it's exactly what we try to do (which is not that smart, indeed). Look at my edit, maybe ?
I want to find the duplicates.. So subtracting the original list and the distinct list will give that.. Dont know how to subtract them..
10

The VB version:

Dim duplicates = listOfItems.GroupBy(Function(i) i)_
                            .Where(Function(g) g.Count() > 1)_
                            .[Select](Function(g) g.Key)

C#:

var duplicates = customers.GroupBy(x => x)
                          .Where(g => g.Count() > 1)
                          .Select(g => g.Key);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.