Skip to content

Instantly share code, notes, and snippets.

@jasmin-mistry
Created September 22, 2022 21:23
Show Gist options
  • Save jasmin-mistry/19c4a65435072172e5b5106d74cf60e4 to your computer and use it in GitHub Desktop.
Save jasmin-mistry/19c4a65435072172e5b5106d74cf60e4 to your computer and use it in GitHub Desktop.
ContainsDuplicates C#
using System.Diagnostics;
List<int> numbers = new() { 1,2,3,4,3,5};
if (ContainsDuplicates(numbers))
{
Console.WriteLine("Contains Duplicate? Yes");
}
else
{
Console.WriteLine("Contains Duplicate? No");
}
static bool ContainsDuplicates<T>(IEnumerable<T> enumerable)
{
HashSet<T> knownElements = new();
foreach (var element in enumerable)
{
if (!knownElements.Add(element))
{
return true;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment