How to find whether the List<string>
has duplicate values or not ?
I tried with below code. Is there any best way to achieve ?
var lstNames = new List<string> { "A", "B", "A" }; if (lstNames.Distinct().Count() != lstNames.Count()) { Console.WriteLine("List contains duplicate values."); }
As we know that list can hold duplicate values but will not update if it contains duplicate values.
Try to use GroupBy
and Any
like;
lstNames.GroupBy(n => n).Any(c => c.Count() > 1);
GroupBy
method;
Groups the elements of a sequence according to a specified key selector function and projects the elements for each group by using a specified function.
Any
method, it returns boolean
;
Determines whether any element of a sequence exists or satisfies a condition.
If you're looking for the most efficient way of doing this,
var lstNames = new List<string> { "A", "B", "A" }; var hashset = new HashSet<string>(); foreach(var name in lstNames) { if (!hashset.Add(name)) { Console.WriteLine("List contains duplicate values."); break; } }
will stop as soon as it finds the first duplicate. You can wrap this up in a method (or extension method) if you'll be using it in several places.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With