C #의 정렬 된 집합은 사용자 지정 개체에서 어떻게 작동합니까? [복제]

Dec 14 2020

사용자 지정 개체에 대해 C #에서 정렬 된 집합을 가지고 놀려고하는데 어떤 이유로 정렬 된 집합이 개체의 참조를 사용하여 데이터를 저장하지 않는 것 같습니다.

다음 코드 조각에서는 사용자 지정 IComparer를 사용하여 사용자 지정 클래스의 Counts 속성에 의존합니다. 그러나 어떤 이유로 이것은 추가 기능에 영향을 미치는 것 같습니다. 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);
            }
        }
    }

살펴보고 도와 주셔서 감사합니다!

답변

1 DmitryBychenko Dec 14 2020 at 13:18

Well [Sorted]Set고유 한 항목 만 포함 할 수 있습니다 . 즉, 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왜 그의를 one하고 two있는 동일 에 대한 counter소트 세트. 항목을 추가 할 때 두 번째 항목 ( two)은 무시됩니다.

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

당신이 원하는 경우 로 구분 기준 (하나 Equals와 주문에 대한 다른 IS)이 오래된 좋은 시도 할 수 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);