Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find List has duplicate values in List<string> [duplicate]

Tags:

c#

list

linq

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."); } 
like image 295
Prasad Kanaparthi Avatar asked Jan 16 '13 16:01

Prasad Kanaparthi


People also ask

Can list contains duplicate values?

As we know that list can hold duplicate values but will not update if it contains duplicate values.


2 Answers

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.

like image 99
Soner Gönül Avatar answered Oct 01 '22 23:10

Soner Gönül


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.

like image 39
Rawling Avatar answered Oct 01 '22 23:10

Rawling