If you’re worried about performance, the following code will stop as soon as it finds the first duplicate item – all the other solutions so far require the whole input to be iterated at least once.
var hashset = new HashSet<string>();
if (myList.Where(s => s != null).Any(s => !hashset.Add(s)))
{
// there are duplicates
}
hashset.Add
returns false
if the item already exists in the set, and Any
returns true
as soon as the first true
value occurs, so this will only search the input as far as the first duplicate.