c# - 如何查找 List 在 List<string> 中有重复值

标签 c# linq list

<分区>

如何找到是否List<string>是否有重复值?

我尝试使用以下代码。有什么最好的方法可以实现吗?

var lstNames = new List<string> { "A", "B", "A" };

if (lstNames.Distinct().Count() != lstNames.Count())
{
    Console.WriteLine("List contains duplicate values.");
}

最佳答案

尝试使用GroupByAny之类的;

lstNames.GroupBy(n => n).Any(c => c.Count() > 1);

GroupBy方法;

Groups the elements of a sequence according to a specified key selector function and projects the elements for each group by using a specified function.

Any方法,它返回 boolean;

Determines whether any element of a sequence exists or satisfies a condition.

关于c# - 如何查找 List 在 List<string> 中有重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14363424/

相关文章:

c# - LINQ:将查询表达式转换为使用 lambda

c# - IEnumerable<T>.ToLookup<TKey, TValue>

java - 向 .txt 文件添加新行

c# - 元胞自动机的实现

c# - Azure Cosmos DB 选择 min(int field) 返回 0

c# - NHibernate QueryOver 别名问题

python - 列表编辑的高效算法

c# - 读取二进制文件到 List<T>

c# - 多个提交按钮不会在 aspx 上回发 - 只有最后一个按钮

c# - 如何处理从 CloudPageBlob.BeginUploadFromStream 中引发的异常