How to find List has duplicate values in List<string>
C#LinqListC# Problem Overview
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.");
}
C# Solutions
Solution 1 - C#
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 - C#
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 - C#
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 - C#
var duplicateExists = lstNames.GroupBy(n => n).Any(g => g.Count() > 1);
Solution 5 - C#
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;
}
}