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

2024-11-23 04:12:44
推荐回答(1个)
回答1:

让你的类实现 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;
}
}
}
}