【问题标题】:Sorting of different types in C# ListC# List 中不同类型的排序
【发布时间】:2016-10-13 11:10:53
【问题描述】:

我有一个 ArrayList:

ArrayList myList = new ArrayList();

它至少包含两个类实例。我想按一个字段对其进行排序,这两个字段都包含。请帮我为 Array.Sort() 方法编写 IComparer,或者给我一个建议,为这个任务创建另一个结构(一个包含两个类实例的列表)。

提前致谢!

【问题讨论】:

  • 如果你需要它们,我建议你为这两个添加一个父接口。然后使用List<T> 而不是ArrayList 你可以只使用linq 的.OrderBy

标签: c# sorting arraylist


【解决方案1】:

类似这样的:

  public sealed class MyComparer: System.Collections.IComparer {
    // We want just one Comparer instance
    public static MyComparer Comparer {
      get;
    } = new MyComparer();

    private MyComparer() {
    }

    public int Compare(object x, object y) {
      if (Object.ReferenceEquals(x, y))
        return 0;
      else if (Object.ReferenceEquals(x, null))
        return -1;
      else if (Object.ReferenceEquals(y, null))
        return 1;

      // Providing that the fields of interest are of type int 
      int leftField = (x is FirstType) 
        ? ((FirstType) x).FieldOfInterest1 
        : ((SecondType) x).FieldOfInterest2;

      int rightField = (y is FirstType) 
        ? ((FirstType) y).FieldOfInterest1 
        : ((SecondType) y).FieldOfInterest2;

      return leftField.CompareTo(rightField);   
    }
  }

  ...

  ArrayList myList = new ArrayList();

  ...

  myList.Sort(MyComparer.Comparer); 

但请记住,ArrayList 是一个过时类,请尝试将您的设计至少更改为List<Object> 或(更好的选择)List<SomeBaseClassOrInterface>

【讨论】:

  • myList.Sort(MyComparer.Comparer.Compare);
  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2011-09-23
  • 1970-01-01
  • 2012-10-20
  • 1970-01-01
  • 1970-01-01
  • 2018-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多