Test if all values in a list are unique

后端 未结 8 1970
温柔的废话
温柔的废话 2020-12-03 09:22

I have a small list of bytes and I want to test that they\'re all different values. For instance, I have this:

List theList = new List

        
8条回答
  •  我在风中等你
    2020-12-03 10:11

    Here's another approach which is more efficient than Enumerable.Distinct + Enumerable.Count (all the more if the sequence is not a collection type). It uses a HashSet which eliminates duplicates, is very efficient in lookups and has a count-property:

    var distinctBytes = new HashSet(theList);
    bool allDifferent = distinctBytes.Count == theList.Count;
    

    or another - more subtle and efficient - approach:

    var diffChecker = new HashSet();
    bool allDifferent = theList.All(diffChecker.Add);
    

    HashSet.Add returns false if the element could not be added since it was already in the HashSet. Enumerable.All stops on the first "false".

提交回复
热议问题