.net - How do I verify a collection of values is unique (contains no duplicates) in C# -


surely there easy way verify collection of values has no duplicates [using default comparison of collection's type] in c#/.net ? doesn't have directly built in should short , efficient.

i've looked lot keep hitting examples of using collection.count() == collection.distinct().count() me inefficient. i'm not interested in result , want bail out detect duplicate, should case.

(i'd love delete question and/or answer if can point out duplicates)

okay, if want out duplicate found, it's simple:

// todo: add overload taking iequalitycomparer<t> public bool allunique<t>(this ienumerable<t> source) {     if (source == null)     {         throw new argumentnullexception("source");     }     var distinctitems = new hashset<t>();     foreach (var item in source)     {         if (!distinctitems.add(item))         {             return false;         }     }     return true; } 

... or use all, you've shown. i'd argue simpler understand in case... or if do want use all, i'd @ least separate creation of set method group conversion, clarity:

public static bool isunique<t>(this ienumerable<t> source) {     // todo: validation     var distinctitems = new hashset<t>();     // add return false if element exists. if     // every element added, must unique.     return source.all(distinctitems.add); } 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -