How to find List has duplicate values ​​in List <string>

How to determine if List<string> duplicate values?

I tried with the code below. Is there a better way to achieve?

 var lstNames = new List<string> { "A", "B", "A" }; if (lstNames.Distinct().Count() != lstNames.Count()) { Console.WriteLine("List contains duplicate values."); } 
+45
list c # linq
Jan 16 '13 at 16:46
source share
5 answers

Try using GroupBy and Any like;

 lstNames.GroupBy(n => n).Any(c => c.Count() > 1); 

GroupBy method;

Groups the elements of the sequence in accordance with the specified key of the selector function and designs the elements for each group using the specified function.

Any , it returns boolean ;

Determines if any element of a sequence exists or satisfies a state.

+69
Jan 16 '13 at 16:50
source share

If you are looking for the most effective way to do 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; } } 

stops as soon as it finds the first duplicate. You can wrap it with a method (or an extension method) if you use it in several places.

+34
Jan 16 '13 at 16:55
source share

A generic and compact version of the hash-based response extension:

 public static bool AreAnyDuplicates<T>(this IEnumerable<T> list) { var hashset = new HashSet<T>(); return list.Any(e => !hashset.Add(e)); } 
+21
Nov 11 '13 at 16:42
source share
 var duplicateExists = lstNames.GroupBy(n => n).Any(g => g.Count() > 1); 
+11
Jan 16
source share

How about trying to convert to a dictionary.

 public bool HasDuplicates(List<String> lstNames) { try { var test = lstNames.ToDictionary(x => x, y => y); return false; } catch (Exception ex) { return true; } } 
-2
Jun 14 '17 at 3:45
source share



All Articles