0

I want to check whether some property is unique in an enumerable:

var Prop_is_unique = new[]{
  new{Prop="A"},
  new{Prop="B"}
};

var Prop_is_not_unique = new[]{
  new{Prop="A"},
  new{Prop="C"},
  new{Prop="B"},
  new{Prop="C"} // uh oh
};

Is there an elegant way to check uniqueness of a property with LINQ to objects? Something along the lines of:

Prop_is_unique.IsUnique(x => x.Prop); // returns true
Prop_is_not_unique.IsUnique(x => x.Prop); // returns false

Is there a simple and elegant solution with LINQ to objects or do I have to write my own extension method?

D.R.
  • 20,268
  • 21
  • 102
  • 205
  • 1
    Not unique = If count of distinct is not equal to count of all. – Sinatr Mar 31 '16 at 11:37
  • Just realized that I can simply use `e.Select(x => x.Prop).ContainsDuplicates()` where `ContainsDuplicates()` has already been asked before. – D.R. Mar 31 '16 at 11:39
  • 1
    @Sinatr nope, the answers in your dupe are less efficient, they need to enumerate the whole sequence even when a dupe is found – Lucas Trzesniewski Mar 31 '16 at 11:41
  • If I have to write my own extension method, I prefer to write a more performant one of course. See also, that I closed with a duplicate of myself ;-) – D.R. Mar 31 '16 at 11:43

0 Answers0