C# C# Custom Comparer for Tuples Based on Item1

问题描述 投票:0回答:0

我正在使用 .Net Framework 4.8 和 C# 5.0

我在代码中使用 SortedSet 类对象。它们被定义为

SortedSet<Tuple<int, MyEnum1, MyStruct>> sortedSet1;
SortedSet<Tuple<int, MyEnum2, MyStruct>> sortedSet2;

结构体 MyStruct 实现了一个 CompareTo() 方法。

我只想根据第一项Item1比较元组。 我可以将这些排序集初始化为:

sortedSet1 = new SortedSet<Tuple<int, MyEnum1, MyStruct>>(new MyCustomComparer());

地点:

private class MyCustomComparer : Comparer<Tuple<int, MyEnum1, MyStruct>>
{
    public override int Compare(Tuple<int, MyEnum1, MyStruct> x, Tuple<int, MyEnum1, MyStruct> y)
    {
        // by int value only
        return x.Item1.CompareTo(y.Item1);
    }
}

并为 sortedSet2 等重复相同的比较器

因为我可能有几个这样的排序集,我希望避免重复自定义比较器。因此,我正在寻找一种方法来对所有这些类型的排序集使用单个比较器。我尝试了多种方法,但我似乎无法创建一个适用于所有这些排序集的比较器。到目前为止,我在网上找到的最接近的是:

public class MyCustomComparer<T> : IComparer
{
   private int itemPosition;
   private int multiplier = -1;

   public MyCustomComparer(int component) : this(component, true)
   { }

   public MyCustomComparer(int component, bool descending)
   {
      if (! descending) multiplier = 1;

      if (component <= 0 || component > 6)
         throw new ArgumentException("The component argument is out of range.");

      itemPosition = component;
   }
   
   public int Compare(object x, object y)
   {       
      var tX = x as Tuple<T1, T2, T3>;
       
      if (tX == null)
      { 
         return 0;
      }   
      else
      {
         var tY = y as Tuple<T1, T2, T3>;
         switch (itemPosition)
         {
            case 1:
               return Comparer<T1>.Default.Compare(tX.Item1, tY.Item1) * multiplier;
            case 2:
               return Comparer<T2>.Default.Compare(tX.Item2, tY.Item2) * multiplier;
            case 3:
               return Comparer<T3>.Default.Compare(tX.Item3, tY.Item3) * multiplier;
            default:
               return Comparer<T1>.Default.Compare(tX.Item1, tY.Item1) * multiplier;
         }
      }
   }

此代码不适用于初始化

sortedSet1 = new SortedSet<Tuple<int, MyEnum1, MyStruct>>(new MyCustomComparer<Tuple<int, MyEnum1, MyStruct>>(1));

因为泛型参数T1、T2、T3未知。

我试过将上面的代码修改为

public class MyCustomComparer<T1, T2, T3> : IComparer
{ ... }

然后我的初始化

sortedSet1 = new SortedSet<Tuple<int, MyEnum1, MyStruct>>(new MyCustomComparer<T1,T2,T3>(1));

无法工作。我收到错误 CS1502 和 CS1503:

参数 1:无法从“MyCustomComparer”转换为“System.Collections.Generic.IComparer>”

我已经按照这些思路尝试了许多其他变体,但似乎没有任何效果。我想这可以实现,但我似乎找不到办法做到这一点。任何帮助将不胜感激。谢谢。

c# tuples compare icomparer
© www.soinside.com 2019 - 2024. All rights reserved.