Created
September 22, 2022 21:23
-
-
Save jasmin-mistry/19c4a65435072172e5b5106d74cf60e4 to your computer and use it in GitHub Desktop.
ContainsDuplicates C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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