C#对集合进行排序_第1页
C#对集合进行排序_第2页
C#对集合进行排序_第3页
C#对集合进行排序_第4页
C#对集合进行排序_第5页
全文预览已结束

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

第C#对集合进行排序输出结果:

从上面的截图中可以看出,Sort()方法默认按照元素的大小进行从小到大的排序,为什么调用Sort()方法就能按照元素的大小进行从小到大的排序呢?其实现原理是什么呢?我们能不能自定义排序规则呢?带着这些问题,我们先来看看Sort()方法的定义,在Sort()方法上面按F12转到定义:

从截图中可以看出,Sort()方法使用了几个重载的方法。可以传递给它的参数有泛型委托ComparisonTcomparison和泛型接口IComparerTcomparer,以及一个范围值和泛型接口IComparerTcomparer。只有集合中的元素实现了IComparableT接口,才能使用不带参数的Sort()方法。我们在这里实现IComparerT接口来创建一个自定义类型的排序功能。

1、定义一个Student类,包括姓名和分数两个属性,可以按照姓名或分数进行排序,Student类定义如下:

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Text;

usingSystem.Threading.Tasks;

namespaceCustomerSort

publicclassStudent

publicstringName{get;set;}

publicdoubleScore{get;set;}

}

2、在定义一个枚举,表示排序的种类,即是按照Name排序还是按照Score排序:

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Text;

usingSystem.Threading.Tasks;

namespaceCustomerSort

///summary

///排序的种类

////summary

publicenumCompareType

Name,

Score

}

3、实现IComparer接口

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Text;

usingSystem.Threading.Tasks;

namespaceCustomerSort

///summary

///StudentComparer自定义排序规则类实现IComparable接口

////summary

publicclassStudentComparer:IComparerStudent

privateCompareType_compareType;

///summary

///通过构造函数给_compareType赋值

////summary

///paramname="compareType"/param

publicStudentComparer(CompareTypecompareType)

_compareType=compareType;

///summary

///实现IComparer接口的Compare

////summary

///paramname="other"/param

///returns/returns

publicintCompare(Studentx,Studenty)

if(x==nully==null)

return0;

if(x==null)

return-1;

if(y==null)

return1;

switch(_compareType)

caseCompareType.Name:

returnstring.Compare(x.Name,y.Name);

break;

caseCompareType.Score:

returnx.Score.CompareTo(y.Score);

break;

default:

thrownewArgumentException("无效的比较类型");

}

4、在Main()方法中调用:

先按照Name进行排序:

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Text;

usingSystem.Threading.Tasks;

namespaceCustomerSort

classProgram

staticvoidMain(string[]args)

//Listintlist=newListint

//list.Add(1);

//list.Add(5);

//list.Add(2);

//list.Add(6);

//list.Add(3);

//list.Add(4);

//Console.WriteLine("*****排序前*****");

//foreach(variteminlist)

//Console.WriteLine(item.ToString());

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论