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
Prasad Kanaparthi Jan 16 '13 at 16:46 2013-01-16 16:46
source share5 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
Soner Gönül Jan 16 '13 at 16:50 2013-01-16 16:50
source shareIf 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
Rawling Jan 16 '13 at 16:55 2013-01-16 16:55
source shareA 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
Zoltán Tamási Nov 11 '13 at 16:42 2013-11-11 16:42
source share var duplicateExists = lstNames.GroupBy(n => n).Any(g => g.Count() > 1); +11
Nasmi Sabeer Jan 16 2018-12-16T00: 00Z
source shareHow 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
Clinton Ward Jun 14 '17 at 3:45 2017-06-14 03:45
source share