在VB.NET中查找字符串列表中的重复项

7

我有一个 customers 字符串列表,想要查找其中的重复客户。

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

但是我遇到了以下异常:
InvalidCastException
Unable to cast object of type '<ExceptIterator>d__99`1[System.String]' to type

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

这是在列表中查找重复项的正确方法吗?
2个回答

11
customers = customers.GroupBy(Function(m) m) _
                 .Where(Function(g) g.Count() > 1) _
                 .Select(Function(g) g.Key).ToList

谢谢,但是Except似乎没有去除重复项。在这一步之后,客户数量为0。(customers.count = 581,customers.Distinct.ToList.count = 575) - Raj
@emaillenin 是的,因为这正是我们试图做的(实际上并不那么聪明)。看看我的编辑,也许可以? - Raphaël Althaus
我想要找到重复的元素。通过从原始列表中减去不同的列表,可以得到它们。但是不知道如何进行减法运算。 - Raj
感谢@RaphaëlAlthaus的好解释。 - HootanHT

10

VB版本:

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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接