如何在List<string>中查找List有重复值 [英] How to find List has duplicate values in List<string>
本文介绍了如何在List<string>中查找List有重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何判断List
是否有重复值?
How to find whether the List<string>
has duplicate values or not ?
我尝试使用以下代码.有没有最好的方法来实现?
I tried with below code. Is there any best way to achieve ?
var lstNames = new List<string> { "A", "B", "A" };
if (lstNames.Distinct().Count() != lstNames.Count())
{
Console.WriteLine("List contains duplicate values.");
}
推荐答案
尽量使用 GroupBy
和 Any
like;
Try to use GroupBy
and Any
like;
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
方法,它返回布尔值
;
确定序列的任何元素是否存在或满足条件.
Determines whether any element of a sequence exists or satisfies a condition.
这篇关于如何在List<string>中查找List有重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文