4

Amazingly, I have not found 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. That mean, i want to get a bool.

For Example:

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

This is maybe a solution I've ended with (I have not tested extensively 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 would not be any simpler solution (I really have not found one)

Cœur
  • 37,241
  • 25
  • 195
  • 267
monty.py
  • 2,511
  • 1
  • 17
  • 29
  • You dont need the final `Select(y => y)` but other than that this or the current answer will do fine. – Jamiec Sep 03 '15 at 12:04
  • listWithMultipleEntries.Distinct().Count() == listWithMultipleEntries.Count; – Amir Popovich Sep 03 '15 at 12:04
  • 1
    Why does anybody use `Count()`? In most of the answers (and this question) a `.Skip(1).Any()` would completely work and would be much faster if you apply it on an `IEnumerable` that is not a `ICollection`. – Oliver Sep 03 '15 at 12:11
  • @Oliver Can you give the whole linq statement please? – monty.py Sep 03 '15 at 12:14
  • @veritas: Here we go: `listToCheck.GroupBy(x => x).Where(g => g.Skip(1).Any()).Any()`. But I would remove the last `Any()` and iterate over the result to give feedback about what occurs multiple times. – Oliver Sep 03 '15 at 13:06

5 Answers5

8

The group by option is probably the best but you could also do

if (listToCheck.Distinct().Count() != listToCheck.Count())
{
    // Do sth.
}
TomDoesCode
  • 3,580
  • 2
  • 18
  • 34
2

this should be the most efficient way to determine if a 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 ...
}
fubo
  • 44,811
  • 17
  • 103
  • 137
1

I'd use ExtensionMethod for such check. You can check if there are duplicates in many ways, but one of the simplest is:

public static bool ContainsDuplicates<T>(this IEnumerable<T> list)
{
    return list.Any(element => list.Count(e => e.Equals(element)) > 1);
}
Fka
  • 6,044
  • 5
  • 42
  • 60
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;
Micke
  • 2,251
  • 5
  • 33
  • 48
0

Other solution might be to compare elements indexes :

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

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

        Console.WriteLine(hasDuplicates);

Output : true

Fabjan
  • 13,506
  • 4
  • 25
  • 52