Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to find out if IEnumerable<> has unique values

Tags:

c#

.net

linq

I have a lot of code in which I do something like this

bool GetIsUnique(IEnumerable<T> values)
{
    return values.Count() == values.Distinct().Count;
}

Is there a better faster nicer way to do this?

like image 999
Gluip Avatar asked Mar 22 '11 12:03

Gluip


People also ask

How do I know if IEnumerable has an item?

enumerable. Any() is the cleanest way to check if there are any items in the list.

How do you find the IEnumerable value?

We can get first item values from IEnumerable list by using First() property or loop through the list to get respective element. IEnumerable list is a base for all collections and its having ability to loop through the collection by using current property, MoveNext and Reset methods in c#, vb.net.

What is distinct Linq?

C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source. It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL).

How do you check if there is anything in an IEnumerable?

If you ever have an IEnumerable and need to determine if there’s anything in it, you might write code like this: Since calling Count () will iterate over the entire collection, you can replace this with Any () which will try to iterate over the first object (if its exists).

What is the return type of IEnumerable?

IEnumerable.Any () will return true if there are any elements in the sequence and false if there are no elements in the sequence. This method will not iterate the entire sequence (only maximum one element) since it will return true if it makes it past the first element and false if it does not.

How do you find the unique values in a list?

Find unique values in a column To find distinct or unique values in a list, use one of the following formulas, where A2 is the first and A10 is the last cell with data. How to find unique values in Excel: =IF (COUNTIF ($A$2:$A$10, $A2)=1, "Unique", "")

Why is there a count () method in an IEnumerable?

Instead there’s a Count () method. The fact that its a method here indicates that it’s not merely access to a known piece of data, its an expensive call which will iterate over the collection to determine the count. If you ever have an IEnumerable and need to determine if there’s anything in it, you might write code like this:


1 Answers

I would make this a nice extension method

public static bool IsUnique<T>(this IEnumerable<T> list)
{
    var hs = new HashSet<T>();
    return list.All(hs.Add);  
}

Checks that all items can be added to a HashSet.

like image 162
Jamiec Avatar answered Sep 27 '22 19:09

Jamiec