Checking List of String for Duplication

In order to explain this blog. Let's create a list of string with the below values in it: 
  1. List<string> lst = new List<string>();  
  2.   
  3. lst.Add("Abstract");  
  4. lst.Add("Sealed");  
  5. lst.Add("Interface");  
  6. lst.Add("Abstract");  
  7. lst.Add("Singleton");  
Now, we would make a query to know whether the above list contain duplicate values or not.

The query is as below: 
  1. var anyDuplicate = lst.GroupBy(x => x).Any(y => y.Count() > 1);  
In this query we are checking the values of the list in the same list itself . The query returns True if there are any duplicates in the list and return False if all the members are unique 
 
We can also use the same query (with some modifications) for checking if all the members of the list are unique. The query is as below: 
  1. var unique = lst.GroupBy(x => x).Any(y => y.Count() == 1);  
Here we are just checking that the count of a particular value should not be more than "1" in the list.

It returns True if the list is unique and returns False otherwise.

Hope it Helped  
Thanks
Ebook Download
View all
Learn
View all