现有一个对象数组,如何按照不同字段对其排序?

xinghuan123432 2011-08-29 09:25:45
public class Student
{
public int _ID;

public int ID
{
get { return _ID; }
set { _ID = value; }
}
private string _name;

public string Name
{
get { return _name; }
set { _name = value; }
}
}

Student[] stu=new Student[5];

Student s1 = new Student();
s1.ID = 1;
s1.Name = "张三";
stu[1] = s1;

Student s2 = new Student();
s2.ID = 2;
s2.Name = "李四";
stu[2] = s2;

Student s3 = new Student();
s3.ID = 3;
s3.Name = "王五";
stu[3] = s3;

Student s4 = new Student();
s4.ID = 4;
s4.Name = "阿二";
stu[4] = s4;

Array.Sort???
...全文
169 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
q107770540 2011-08-29
  • 打赏
  • 举报
回复

void Main()
{

Student[] stu=new Student[4];

Student s1 = new Student();
s1.ID = 1;
s1.Name = "张三";
stu[0] = s1;

Student s2 = new Student();
s2.ID = 2;
s2.Name = "李四";
stu[1] = s2;

Student s3 = new Student();
s3.ID = 4;
s3.Name = "王五";
stu[2] = s3;

Student s4 = new Student();
s4.ID = 3;
s4.Name = "阿二";
stu[3] = s4;
//order by 1 protety
stu=stu.OrderBy(s=>s.ID).ToArray();

//order by 2 potety
stu=(from s in stu
orderby s.ID,s.Name descending
select s).ToArray();


}
public class Student
{
public int _ID;

public int ID
{
get { return _ID; }
set { _ID = value; }
}
private string _name;

public string Name
{
get { return _name; }
set { _name = value; }
}
}

ciznx 2011-08-29
  • 打赏
  • 举报
回复
抱歉,上一楼中 delegate 委托应该返回的是 int 型,应该将 return s1.ID > S2.ID; 改为 return s1.ID - s2.ID;
flyerwing 2011-08-29
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 fangxinggood 的回复:]
为什么不用Linq?

stu = stu.OrderBy(s => s.Name);
stu = stu.OrderBy(s => s.ID);
[/Quote]
LINQ好用,大家好才是真的好。
ciznx 2011-08-29
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 fangxinggood 的回复:]
为什么不用Linq?
stu = stu.OrderBy(s => s.Name);
stu = stu.OrderBy(s => s.ID);
[/Quote]

显然这用的不是 .net 的高版本,不用建议用 Linq


另外,实现 IComparable 接口也不能解决问题,楼主希望按不同字段进行排序,换言之,想按哪个字段就按哪个字段,而不是像 IComparable 中那样只能按一两个既字字段排序


最方便的解决办法就是构建一个泛型 List,然后调用其 Sort 方法:

List<Student> students = new List<Student>();


public List<Student> SortById(List<Student> sts)
{
return sts.Sort(delegate(Student s1, Student s2){
return s1.ID > S2.ID;
});
}

//SortByName 的实现自己依此类推

huangwenquan123 2011-08-29
  • 打赏
  • 举报
回复

用list<>添加
list.Sort(new CompareStudent());排序,
List<Student> list = new List<Student>();
public class CompareStudent : IComparer<Student>
{
public int Compare(Student x, Student y)
{
return y.ID - x.ID;
}
}
或者写个委托,传递方法。
机器人 2011-08-29
  • 打赏
  • 举报
回复
为什么不用Linq?

stu = stu.OrderBy(s => s.Name);
stu = stu.OrderBy(s => s.ID);
zhujiazhi 2011-08-29
  • 打赏
  • 举报
回复

public class Student : IComparable
{
#region IComparable 成员

public int CompareTo(object obj)
{
throw new NotImplementedException();
}

#endregion
}

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧