C#如何实现在ArrayLis中Sort()方法,使其按自定义类中的某个元素进行排序
如:classA{intid;Stringname;}将A的对象加入ArrayList中,调用Sort()方法,使其按A中的id排序,请高手指点,谢谢,最好有成功的示例代...
如:class A
{
int id;
String name;
}
将A的对象加入ArrayList中,调用Sort()方法,使其按A中的id排序,请高手指点,谢谢,最好有成功的示例代码!!! 展开
{
int id;
String name;
}
将A的对象加入ArrayList中,调用Sort()方法,使其按A中的id排序,请高手指点,谢谢,最好有成功的示例代码!!! 展开
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;
}
}
}
}
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;
}
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询