LINQ <string> Checklist for Multiple Entries

Surprisingly, I did not find a simple solution for the following behavior.

I have a list and I just want to check (with Linq) if there are multiple entries in it. This means I want to get bool.

Example:

List<string> listWithMultipleEntries = new List<string>()
{
    "Hello",
    "World",
    "!",
    "Hello"
};

Perhaps this is the solution I ended up with (I haven't tested a lot, but it seems to work)

if (listToCheck.GroupBy(x => x).Where(g => g.Count() > 1).Select(y => y).Any())
{
    // Do something ...
}

but I would be surprised if there was no simpler solution (I really did not find it)

+4
source share
5 answers

Choosing a group of choice is probably the best, but you can also do

if (listToCheck.Distinct().Count() != listToCheck.Count())
{
    // Do sth.
}
+8
source

this should be the most efficient way to determine if the list has duplicates or not

public static bool HasDuplicates<T>(this IEnumerable<T> list)
{
    HashSet<T> distinct = new HashSet<T>();
    foreach (var s in list)
    {
        if (!distinct.Add(s))
        {
            return true;
        }
    }
    return false;
}

so you can ..

if (listToCheck.HasDuplicates())
{
    // Do something ...
}
+2

ExtensionMethod . , -, :

public static bool ContainsDuplicates<T>(this IEnumerable<T> list)
{
    return list.Any(element => list.Count(e => e.Equals(element)) > 1);
}
+1

Two solutions, one using GroupBy(), the other using Disctinct():

var hasDuplicates = listWithMultipleEntries.GroupBy(x => x).Any(g => g.Count() > 1);

var hasDuplicates = listWithMultipleEntries.Distinct().Count() != listWithMultipleEntries.Count;
+1
source

Another solution might be to compare element indices:

        List<string> list = new List<string>()
        {
            "Hello",
            "World",
            "!",
            "Hello"
        };

        bool hasDuplicates = list.Where((l, i) => list.LastIndexOf(l) != i).Any();

        Console.WriteLine(hasDuplicates);

Exit: true

0
source

Source: https://habr.com/ru/post/1605726/


All Articles