排序自定义类的列表 [英] Sorting a list of a custom class

查看:58
本文介绍了排序自定义类的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Web应用程序.我写了一堂课

I am writing a web application. I have written a class

class person{<br />
  string FirstName = "";<br />
  int rank = 0;<br />
  int LastName = "";<br />
}



我有一个人"列表,并想按等级-IE对其进行排序.最高排名第一

例如.

假设我有一个叫bob的级别为2的人,一个叫rob的级别为4的人,还有一个叫wob的级别为1的人.

(我非常想起名字)

我想对这个列表进行排序,以便结果如下:



I have a list of "people" and want to sort them by rank - IE. highest rank first

for example.

Say I have someone called bob at a rank of 2 and someone called rob with a rank of 4 and someone called wob with a rank of 1

(I''m great with coming up with names)

I want to sort this list so the outcome would be this:

rob - 4<br />
bob - 2<br />
wob - 1



有人可以帮忙吗?



Can anyone help?

推荐答案

public class Person{
	public string FirstName {get;set;}
	public int Rank {get;set;}
	public string LastName {get;set;}
}

List<person> personList = new List<person>();
personList.Add(new Person(){ FirstName="bob", Rank=2 });
personList.Add(new Person(){ FirstName="wob", Rank=1 });
personList.Add(new Person(){ FirstName="rob", Rank=4 });

var result =  from v in (from p in personList
                         select p).OrderByDescending(x=>x.Rank)
              select new
                  {
		ResultValue = String.Format("{0} - {1}",v.FirstName,v.Rank)
	      };


这将导致


This would result

rob - 4
bob - 2
wob - 1


您困在哪里?要开始使用,可以使用IComparable< T>.界面以创建列表的自定义排序.请参考以下链接:

http://msdn.microsoft.com/en-us/library/4d7sx9hd.aspx [ ^ ]

http://addinit.com/node/50 [
Where are you stuck? To get you started, you can use the IComparable<T> interface to create custom sorting of lists. Refer to the following link:

http://msdn.microsoft.com/en-us/library/4d7sx9hd.aspx[^]

http://addinit.com/node/50[^]

Hope this helps!


List<person> ToBeSortedList ;//modify to appropriate list name

List<person> SortedbyRankPersonList = (ToBeSortedList.OrderByDescending(c => c.rank)).ToList();



谢谢,

Kuthuparakkal



Thanks,

Kuthuparakkal


这篇关于排序自定义类的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆