如:class A
{
int id;
String name;
}
将A的对象加入ArrayList中,调用Sort()方法,使其按A中的id排序,请高手指点,谢谢,最好有成功的示例代码!!!
C#如何实现在ArrayLis中Sort()方法,使其按自定义类中的某个元素进行排序
答案:2 悬赏:0 手机版
解决时间 2021-03-03 21:28
- 提问者网友:相思似海深
- 2021-03-03 01:36
最佳答案
- 五星知识达人网友:话散在刀尖上
- 2021-03-03 03:06
让你的类实现 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;
}
}
}
}
全部回答
- 1楼网友:醉吻情书
- 2021-03-03 03:18
public class a
{
public int id;
public string name;
}
这样定义更方便
list<a> list = new list<a>();
list<a> newlist= list.orderby(o => o.id).tolist();
用linq这样很方便查询排序
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯