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
5 answers
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