'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:[1]

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 2:[2]

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 3:[3]

var duplicateExists = lstNames.GroupBy(n => n).Any(g => g.Count() > 1);

Solution 4:[4]

 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;
    }
}  

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Zoltán Tamási
Solution 3 Nasmi Sabeer
Solution 4 SUNIL DHAPPADHULE