C# 如何在 List<string> 中查找 List 有重复值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14363424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find List has duplicate values in List<string>
提问by Prasad Kanaparthi
How to find whether the List<string>
has duplicate values or not ?
如何查找是否List<string>
有重复值?
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.");
}
采纳答案by Soner G?nül
Try to use GroupBy
and Any
like;
尝试使用GroupBy
和Any
喜欢;
lstNames.GroupBy(n => n).Any(c => c.Count() > 1);
GroupBy
method;
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
method, it returns boolean
;
Any
方法,它返回boolean
;
Determines whether any element of a sequence exists or satisfies a condition.
确定序列的任何元素是否存在或满足条件。
回答by Nasmi Sabeer
var duplicateExists = lstNames.GroupBy(n => n).Any(g => g.Count() > 1);
回答by Rawling
If you're looking for the most efficient way of doing this,
如果您正在寻找最有效的方法,
var lstNames = new List<string> { "A", "B", "A" };
var hashset = new HashSet<string>();
foreach(var name in lstNames)
{
if (!hashset.Add(name))
{
Console.WriteLine("List contains duplicate values.");
break;
}
}
will stop as soon as it finds the first duplicate. You can wrap this up in a method (or extension method) if you'll be using it in several places.
一旦找到第一个重复项就会停止。如果您将在多个地方使用它,您可以将其封装在一个方法(或扩展方法)中。
回答by Zoltán Tamási
A generalized and compact extension version of the answer based on hash technique:
基于散列技术的答案的通用和紧凑扩展版本:
public static bool AreAnyDuplicates<T>(this IEnumerable<T> list)
{
var hashset = new HashSet<T>();
return list.Any(e => !hashset.Add(e));
}
回答by Sunil Dhappadhule
class Program
{
static void Main(string[] args)
{
var listFruits = new List<string> { "Apple", "Banana", "Apple", "Mango" };
if (FindDuplicates(listFruits)) { WriteLine($"Yes we find duplicate"); };
ReadLine();
}
public static bool FindDuplicates(List<string> array)
{
var dict = new Dictionary<string, int>();
foreach (var value in array)
{
if (dict.ContainsKey(value))
dict[value]++;
else
dict[value] = 1;
}
foreach (var pair in dict)
{
if (pair.Value > 1)
return true;
else
return false;
}
return false;
}
}