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

前端 未结 7 2163
轻奢々
轻奢々 2021-02-19 20:00

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

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


        
7条回答
  •  暖寄归人
    2021-02-19 20:28

    Two basic rules:

    1. The easiest way to read and understand is almost always the best way to code something. That code is deliciously easy to read, so I'd say you're good to go.
    2. Performance ("faster") should only be a concern if you can prove that this is the method that's slowing your program down, or if you're building a library that other people will have access to without having access to the source code.

    The other methods are going to be faster (they'll short circuit when a repeated value is found, returning false), but, I'd still stick with your version if it were my code.

提交回复
热议问题