C# SortedSet and equality

前端 未结 3 1886
清酒与你
清酒与你 2021-01-04 06:48

I am a bit puzzled about the behaviour of SortedSet, see following example:

public class Blah
{
    public double Value { get; private set; }

    public Bla         


        
3条回答
  •  执念已碎
    2021-01-04 06:51

    You can do this if you provide an alternate comparison when the Values are equal and the Compare method would otherwise return 0. In most cases this would probably just defer the problem instead of solving it. As others have noted, the SortedSet discards duplicates and when you provide a custom comparer it uses that to determine duplicity.

        static void Main(string[] args)
        {
            var blahs = new List
                            {
                                new Blah(1, 0), new Blah(2, 1),
                                new Blah(3, 2), new Blah(2, 3)
                            };
    
            blahs.Add(blahs[0]);
    
            //contains all 4 entries
            var set = new HashSet(blahs);
    
            //contains all 4 entries
            var sortedset = new SortedSet(blahs, new BlahComparer());
    
        }
    }
    
    public class Blah
    {
        public double Value { get; private set; }
    
        public Blah(double value, int index)
        {
            Value = value;
            Index = index;
        }
    
        public int Index { get; private set; }
    
        public override string ToString()
        {
            return Value.ToString();
        }
    }
    
    public class BlahComparer : Comparer
    {
        public override int Compare(Blah x, Blah y)
        {
            // needs null checks
            var referenceEquals = ReferenceEquals(x, y);
            if (referenceEquals)
            {
                return 0;
            }
            var compare = Comparer.Default.Compare(x.Value, y.Value);
            if (compare == 0)
            {
                compare = Comparer.Default.Compare(x.Index, y.Index);
            }
            return compare;
        }
    }
    

提交回复
热议问题