C# 如何按对象属性之一对对象的ArrayList排序?

C# 如何按对象属性之一对对象的ArrayList排序?,c#,.net,arraylist,C#,.net,Arraylist,如何按对象属性之一对对象的ArrayList排序 请不要建议任何与列表相关的技巧。对于我当前的软件,使用列表是不可能的。您需要为您的实体实施IComparer,例如: public class MyClassComparer : IComparer<MyClass> { public int Compare(MyClass _x, MyClass _y) { return _x.MyProp.CompareTo(_y.MyProp); } }

如何按对象属性之一对对象的ArrayList排序


请不要建议任何与
列表相关的技巧。对于我当前的软件,使用
列表
是不可能的。

您需要为您的实体实施
IComparer
,例如:

public class MyClassComparer : IComparer<MyClass>
{
    public int Compare(MyClass _x, MyClass _y)
    {
        return _x.MyProp.CompareTo(_y.MyProp);
    }
}

您必须实现自己的比较器,

这是一个使用LinqPad编写的示例,可以帮助您。 大致基于MSDN示例。
您只需要使用自己的类,而不是这里使用的示例

void Main()
{
    ArrayList al = new ArrayList();
    al.Add(new Person() {Name="Steve", Age=53});
    al.Add(new Person() {Name="Thomas", Age=30});

    al.Sort(new PersonComparer());

    foreach(Person p in al)
        Console.WriteLine(p.Name + " " + p.Age);

}

class Person
{
    public string Name;
    public int Age;
}
class PersonComparer : IComparer
{

    int IComparer.Compare( Object x, Object y )  
    {
        if (x == null)
            return (y == null) ? 0 : 1;

        if (y == null)
            return -1;

        Person p1 = x as Person;
        Person p2 = y as Person;

        // Uncomment this to sort by Name 
        // return( (new CaseInsensitiveComparer()).Compare( p1.Name, p2.Name) );

        return( p1.Age - p2.Age );
    }
}

上面有一个例子。您是否尝试过以该示例作为起点?@dasblinkenlight LINQ对非泛型集合不起作用。您可以从
ArrayList
中创建泛型集合,对其进行排序,然后创建新的
ArrayList
,其中包含已排序的项,但我认为这不是一个好主意。正如Steve指出的那样,
ArrayList
上已经定义了
Sort
方法。使用LINQ也是不可选择的,因为我在一个遗留软件上编码,并且被要求不要为此使用LINQ。我的arrayList包含许多对象,如X、Y、Z等,我只想根据一个对象的属性(如Y)对arrayList进行排序。有人能给我一些建议吗?你试过什么?有什么问题吗?你是什么意思?属性应用于类级别,而不是实例级别。你是说财产吗?是否要按特定属性排序?如果对象的类型不同,会发生什么情况?@MarcinJuraszek可以在linq表达式之前使用
ArrayList
上的
Cast
of type
。根据注释,数组可能包含不同的types@PanagiotisKanavos那会有什么变化?方法将保持不变。也许我们可以用接口而不是具体的类来操作,或者用对象来做比较器,用反射来比较东西。这意味着你必须检查每个对象的类型,你不能使用通用比较器。实际上,IComparer没有实现IComparer,所以它不能传递给ArrayList。Sort@PanagiotisKanavos关于IComparer或IComparer呢?是的,这也意味着作者需要替换MyProp等等,但关于实现和问题的小细节并不像我写的那样,IComparer没有实现IComparer,因此您无法使用它,代码无法编译。类型检查和铸造的“小细节”首先是导致问题的原因。谢谢史蒂夫:D这对我有用D非常有用!!
void Main()
{
    ArrayList al = new ArrayList();
    al.Add(new Person() {Name="Steve", Age=53});
    al.Add(new Person() {Name="Thomas", Age=30});

    al.Sort(new PersonComparer());

    foreach(Person p in al)
        Console.WriteLine(p.Name + " " + p.Age);

}

class Person
{
    public string Name;
    public int Age;
}
class PersonComparer : IComparer
{

    int IComparer.Compare( Object x, Object y )  
    {
        if (x == null)
            return (y == null) ? 0 : 1;

        if (y == null)
            return -1;

        Person p1 = x as Person;
        Person p2 = y as Person;

        // Uncomment this to sort by Name 
        // return( (new CaseInsensitiveComparer()).Compare( p1.Name, p2.Name) );

        return( p1.Age - p2.Age );
    }
}