c# - How to validate if a collection contains all unique objects -
i have c# collection of objects not implement iequatable or icomparable. want check if collection contains duplicate objects. i.e. want know if object.referenceequals(x, y) false x , y in list.
how efficiently?
it nice both c# , linq method.
non-linq, when collection implements icollection<t>
or icollection
:
bool allitemsunique = new hashset<yourtype>(yourcollection).count == yourcollection.count;
non-linq, when collection doesn't implement icollection<t>
or icollection
. (this version has better theoretical performance first because break out duplicate found.)
bool allitemsunique = true; var tempset = new hashset<yourtype>(); foreach (yourtype obj in yourcollection) { if (!tempset.add(obj)) { allitemsunique = false; break; } }
linq. (this version's best case performance -- when collection implements icollection<t>
or icollection
-- same first non-linq solution. if collection doesn't implement icollection<t>
or icollection
linq version less efficient.)
bool allitemsunique = yourcollection.distinct().count() == yourcollection.count();
Comments
Post a Comment