Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Check List<string> for multiple entries [duplicate]

Tags:

c#

linq

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)

like image 447
monty.py Avatar asked Dec 14 '22 12:12

monty.py


1 Answers

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

if (listToCheck.Distinct().Count() != listToCheck.Count())
{
    // Do sth.
}
like image 124
TomDoesCode Avatar answered Dec 17 '22 01:12

TomDoesCode