在C#List中排序不同类型

时间:2016-10-13 11:10:54

标签: c# sorting arraylist

我有一个ArrayList:

ArrayList myList = new ArrayList();

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

提前致谢!

1 个答案:

答案 0 :(得分:0)

这样的事情:

  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>