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?
enumerable. Any() is the cleanest way to check if there are any items in the list.
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.
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).
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).
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.
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", "")
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With