Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if all values in a list are unique

Tags:

c#

I have a small list of bytes and I want to test that they're all different values. For instance, I have this:

List<byte> theList = new List<byte> { 1,4,3,6,1 }; 

What's the best way to check if all values are distinct or not?

like image 819
frenchie Avatar asked Aug 18 '13 21:08

frenchie


People also ask

How do you check if all elements in a list is unique?

# Given List Alist = ['Mon','Tue','Wed'] print("The given list : ",Alist) # Compare length for unique elements if(len(set(Alist)) == len(Alist)): print("All elements are unique. ") else: print("All elements are not unique. ")

Is unique in Python?

The unique() function is used to find the unique elements of an array. Returns the sorted unique elements of an array. There are three optional outputs in addition to the unique elements: the indices of the input array that give the unique values.

How do you check unique values in Python?

Using Python's import numpy, the unique elements in the array are also obtained. In the first step convert the list to x=numpy. array(list) and then use numpy. unique(x) function to get the unique values from the list.


2 Answers

bool isUnique = theList.Distinct().Count() == theList.Count(); 
like image 175
juergen d Avatar answered Sep 29 '22 23:09

juergen d


Here's another approach which is more efficient than Enumerable.Distinct + Enumerable.Count (all the more if the sequence is not a collection type). It uses a HashSet<T> which eliminates duplicates, is very efficient in lookups and has a count-property:

var distinctBytes = new HashSet<byte>(theList); bool allDifferent = distinctBytes.Count == theList.Count; 

or another - more subtle and efficient - approach:

var diffChecker = new HashSet<byte>(); bool allDifferent = theList.All(diffChecker.Add); 

HashSet<T>.Add returns false if the element could not be added since it was already in the HashSet. Enumerable.All stops on the first "false".

like image 39
Tim Schmelter Avatar answered Sep 30 '22 00:09

Tim Schmelter