C# 的排序集如何处理自定义对象?

How do sorted sets for c# work with custom objects?

我正在尝试在 c# 中为自定义对象使用排序集,但出于某种原因,似乎排序集可能没有使用对象的引用来存储数据..

在下面的代码片段中,我使用自定义 IComparer 来依赖自定义 class 的计数 属性。但出于某种原因,这似乎影响了添加功能。并且 counter.Add(two) 行不会对集合进行任何添加,即使它是不同的引用并且两个属性具有不同的值。

我错过了什么吗?我对 SortedSets 在 C# 中的工作方式有什么误解吗?

代码片段

    public class SortedStructureTesting
    {
        public void TestingSortedSets()
        {
            SortedSet<CounterSetup> counter = new SortedSet<CounterSetup>(new CompareCounts());

            CounterSetup one = new CounterSetup(1);
            CounterSetup two = new CounterSetup(2);
            CounterSetup three = new CounterSetup(3, 2);

            counter.Add(one);
            counter.Add(two); // Does not work. This value does not get added to the set.
            counter.Add(three);

            var max = counter.Max;
            counter.Remove(max);
            var sec = counter.Max;
            counter.Remove(sec);
        }

        public class CounterSetup
        {
            public static Random random = new Random();
            public CounterSetup(int no, int cnt = 1)
            {
                Number = no;
                Count = cnt;
                Blah = new string(Guid.NewGuid().ToString());
            }

            public int Number { get; private set; }

            public int Count { get; set; }

            public string Blah { get; private set; }
        }

        public class CompareCounts : IComparer<CounterSetup>
        {
            public int Compare(CounterSetup one, CounterSetup two)
            {
                return one.Count.CompareTo(two.Count);
            }
        }
    }

感谢您的浏览和帮助!

那么 [Sorted]Set 只能包含 distinct 个项目;即 Set 不能再有两个相等的项目。您根据 Count 比较项目(将它们视为相等):如果两个项目具有相同的 Count,则它们被视为相等。在你的代码中

  CounterSetup one = new CounterSetup(1);         // one.Count == 1
  CounterSetup two = new CounterSetup(2);         // two.Count == 1
  CounterSetup three = new CounterSetup(3, 2);    // three.Count == 2

你有 one.Count == two.Count == 1 这就是 onetwo 对于 counter 排序集 相等 的原因。添加项目时,第二个(two)将被忽略:

  counter.Add(one);
  counter.Add(two); // Ignored: there's already an item (one) with the same Count
  counter.Add(three);

如果你想要 separated 标准(一个用于 Equals 而另一个用于顺序)你可以尝试旧的 HashSet 你可以表示为在 Linq:

的帮助下订购
  using System.Linq;

  ...

  // Items in counter are unique (based on MyEqualityComparer)
  HashSet<CounterSetup> counter = new HashSet<CounterSetup>(
    new MyEqualityComparer()
  );

  // Now we order counter items by different criterium (here we sort by `Count`)
  var ordered = counter
    .OrderBy(item => item.Count);