How to find List has duplicate values in List<string> [duplicate]
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.");
}
Solution 1:
Try to use GroupBy
and Any
like;
lstNames.GroupBy(n => n).Any(c => c.Count() > 1);
GroupBy
method;
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
;
Determines whether any element of a sequence exists or satisfies a condition.
Solution 2:
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.
Solution 3:
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));
}
Solution 4:
var duplicateExists = lstNames.GroupBy(n => n).Any(g => g.Count() > 1);