C#如何实现在ArrayLis中Sort()方法,使其按自定义类中的某个元素进行排序

如:class A
{
int id;
String name;
}
将A的对象加入ArrayList中,调用Sort()方法,使其按A中的id排序,请高手指点,谢谢,最好有成功的示例代码!!!

让你的类实现 IComparable 接口即可
using System;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
System.Collections.ArrayList list = new System.Collections.ArrayList();
list.Add(new A(0, "张三"));
list.Add(new A(2, "王五"));
list.Add(new A(1, "李四"));

//加入的顺序是 0,2,1

list.Sort();

foreach (A a in list)
{
Console.WriteLine(a.name);
}
Console.Read();
}
}

class A:IComparable
{
int id;
public string name{get;set;}

public A(int id, string name)
{
this.id = id;
this.name = name;
}

public int CompareTo(object obj)
{
var a = obj as A;
if (a.id > this.id)
{
return -1;
}
else if (a.id < this.id)
{
return 1;
}
else
{
return 0;
}
}
}
}
温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网