c#list排序的三种实现方式

c#list排序的三种实现方式

ID:34721998

大小:82.18 KB

页数:3页

时间:2019-03-10

c#list排序的三种实现方式_第1页
c#list排序的三种实现方式_第2页
c#list排序的三种实现方式_第3页
资源描述:

《c#list排序的三种实现方式》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库

1、第一种:实体类实现IComparable接口,而且必须实现CompareTo方法实体类定义如下: ViewCode1classInfo:IComparable2{3publicintId{get;set;}4publicstringName{get;set;}56publicintCompareTo(objectobj){7intresult;8try9{10Infoinfo=objasInfo;11if(this.Id>info.Id)12{13result=0;14}15else16result=1;17returnresult;18}19catch(Ex

2、ceptionex){thrownewException(ex.Message);}20}21} 调用方式如下,只需要用sort方法就能实现对list进行排序。 ViewCode1privatestaticvoidReadAccordingCompare(){2ListinfoList=newList();3infoList.Add(4newInfo(){Id=1,Name="abc"});5infoList.Add(newInfo(){Id=3,Name="rose"});6infoList.Add(newInfo(){Id=2,Na

3、me="woft"});7infoList.Sort();8foreach(varitemininfoList)9{10Console.WriteLine(item.Id+":"+item.Name);11}12} 第二种方法:linqtolist进行排序运用linq实现对list排序,在实体类定义的时候就不需用实现IComparable接口,调用方式如下:ViewCode1privatestaticvoidReadT(stringstr){2ListinfoList=newList();3infoList.Add(4newInfo()

4、{Id=1,Name="woft"});5infoList.Add(newInfo(){Id=3,Name="rose"});6infoList.Add(newInfo(){Id=2,Name="abc"});7Console.WriteLine("ReadT*********************");8IEnumerablequery=null;9query=fromitemsininfoListorderbyitems.Idselectitems;10foreach(variteminquery)11{12Console.WriteLine

5、(item.Id+":"+item.Name);13}14}但是上面两种方式都只能对一个实体属性排序,如果对不同的属性排序的话只能写很多的if进行判断,这样显得很麻烦。且看下面的方式实现根据传入参数进行排序。 ViewCode1privatestaticvoidListSort(stringfield,stringrule)2{3if(!string.IsNullOrEmpty(rule)&&(!rule.ToLower().Equals("desc")

6、

7、!rule.ToLower().Equals("asc")))4{5try6{7Listin

8、foList=GetList();8infoList.Sort(9delegate(Infoinfo1,Infoinfo2)10{11Typet1=info1.GetType();12Typet2=info2.GetType();13PropertyInfopro1=t1.GetProperty(field);14PropertyInfopro2=t2.GetProperty(field);15returnrule.ToLower().Equals("asc")?16pro1.GetValue(info1,null).ToString().CompareTo(

9、pro2.GetValue(info2,null).ToString()):17pro2.GetValue(info2,null).ToString().CompareTo(pro1.GetValue(info1,null).ToString());18});19Console.WriteLine("*****ListSort**********");20foreach(varitemininfoList)21{22Console.WriteLine(item.Id+","+item.Name);23}24}25catch(Exceptionex)26{27C

10、onsole.WriteLine(ex

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。