CList<T>排序_第1页
CList<T>排序_第2页
CList<T>排序_第3页
CList<T>排序_第4页
CList<T>排序_第5页
已阅读5页,还剩9页未读 继续免费阅读

下载本文档

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

文档简介

1、摘要:在面向对象开发过程中我们经常将一组对象放到一个特定集合中,此时我们通常使用泛型集合来存放,常见的如:ListDictionary 等。在使用这些泛型集合时我们有时需要对其进行排序,下面我们就一块看一下List如何进行排序(像Dictionary 也有其相应的排序方式,例如说使用Linq语法方式,今天暂且不说)。主要内容:1. 初始工作2. 默认排序方式3. 通过自定义比较器进行排序4. 设定排序范围5. 总结一、初始工作假设我们有一个 Student 对象,简单起见这个对象只有三个属性,分别是学好、姓名、年龄。E E代码using System;using System.Collecti

2、ons.Generic;using System.Linq;using System.Text;namespace GenericCompareclass Studentpublic Student()public Student( string no, string name, int age)this .No = no;this .Name = name;this .Age = age;public string Noget ;set ;public string Nameget ;set ;public int Age(get set 我们有四个学生,分别存放在List中。田E代码usi

3、ng System;using System.Collections.Generic;using System.Linq;using System.Text;namespace GenericCompare(class Program(static void Main( string args)(List<Student> students=new List<Student>();students.Add(new Student( "001" , "kenshincui", 25);students.Add(new Student

4、( "002" , "miaoer" , 23);students.Add(new Student( "003” , "shenjinjuan", 22);students.Add(new Student( "004" , "nieyanxin" , 24);Console.WriteLine("未进行排序之前:");foreach (Student stin students)( Console.WriteLine(st.No+"," +st.

5、Name+ "," +st.Age+ "");Console.ReadKey();很明显我们往students对象中加入学生的时候并没有顺序,下面我们就一起看一下如何对students 集合按照年龄由小到大来排序。二、默认排序方式如果你查一下List的API的话,我们会看到对于 List的Sort方法有四种重载,首先在这里我们说一下第一种,也就是无参数的情况:List.Sort ()。那么我能不能直接对students集合使用Sort()方法进行排序呢?答案是否定的,如果我们使用下面的方法排序的话系统将抛出System .InvalidOperation

6、Exception 异常。田E代码usingusingusingusingSystem;System.Collections.Generic;System.Linq;System.Text;namespace GenericCompareclass ProgramList<Student> students=new List<Student>();students.Add(newStudent("001" , "kenshincui"students.Add(newStudent("002" , "m

7、iaoer",students.Add(newStudent("003" , "shenjinjuan"students.Add(newStudent("004" , "nieyanxin"Console.WriteLine("未进行排序之前:");string args)foreach (Student stin students),25);23);,22);,24);static void Main( Console.WriteLine(st.No+","+st

8、.Name+ ","+st.Age+ "");Console.WriteLine(students.Sort();foreach (Student st Console.WriteLine(st.No +Console.ReadKey();"List.Sort ()排序之后:");in students)","+ st.Name + st.Age +"");执行上面的代码将抛出如下异常函 C :Wi n d owsXsyst 3 2 c md. exe床进行排能前:101, kenshirtcu

9、i.,.25 :102 r nloer, 23 r133 r s:hienjd.n Juanr 22 7|0* nicynxin24;1st.Sort <>排序之后=处理的异常=System, InualidOperdtionlxccpt ion ;未能比较数组中的两个兀素。System_ArgumentExcept ion :必须至少有个对象实现 I Comparable 在 Sys ten-Collect ions -Comjparer .Compare (Object a, Ob j e c t b> 在 Sis ten-ColleGt ions - Generic .

10、ObjectConpayeP * 1 - Conpai'e (T x, T y> 在 System. Co I lectio ns - Generic .fipraySortHe Iper11. S wapl f Gve at ei'With I terns CT 1 he ye, fCdnpai*ei*'l compapeF, Int32 a, Int32 1)在 Sys ten .Collect ions - Genepic .Iper" 1. QuLckSoi*t <T E J kay 客姓 Int32 LeFI nt32 rig(ht, l

11、Compai*er*l 在 Sys ten. Collect ions .Generic .DrvaSortHe Iper11. Sot (I I nt32 indax InlenQfth> ICompai'ep '1 comparer>内部异常堆栈呷踪的结尾、什 Ssitem.Co Llectxons BGenepac B ArraysHe Ipei*1 i « Sot CT kesr I n七W2 Indlexj. In #32 Lsnarth I Comparer71 comijarer?在 Sys ten. Sort CT J<T t J a

12、rra*/., I nt 32 index, I a t32 length, I Comparer L1 com在 8 Go.Generic .List '1 .Sort < I nt 32 index, Icount P IGonparer11 comparer)Sys ten-Co1lections-Generic.List11.Sort O从图中的提示我们可以看出错误原因是由于进行比较的对象并未有任何一个实现IComparable 接口,因此也就无法完成排序。事实上对于无参Sort()方法是使用Comparer.Default比较器来排序的,而此比较器进行比较时首先就会检查

13、T是否实现了 IComparable 泛型接口,如果实现了则使用该实现。否则将坚持是否实现了IComparable 接口。如果均未实现则引发InvalidOperationException 异常。也就是说如果想使用此方法需要实现ICompara 泛型接口或者IComparable 接口,因此我们暂且修改一下Student 类,实现IComparable 接口(除了这个例子职务后面的例子仍然使用第一步我们建立的Student 类)。首先修改 Student 类,实现IComparable 接口:匿1 E代码using System;using System.Collections.Generi

14、c;using System.Linq;using System.Text;namespace GenericCompareclass Student:IComparablepublic Student() public Student( string no, string name, int age)(this .No = no;this .Name = name;this .Age = age;public string No(get ;set ;public string Name(get ;set ;public int Age(get ;set ;#region IComparabl

15、e 成员public int CompareTo( object obj)(if (obj is Student)(Student tempStudent =obj as Student;return this .Age.CompareTo(tempStudent.Age);throw new NotImplementedException( "obj is not a Student!" );#endregion然后我们再运行程序就会看到可以按照我们的想法去排序了。接着再使用Sort()排序的话就可以看到如下排序成功的界面:1=1 file/ '/F:/CS h

16、pa rp/G e ne n cC o m paf e/G e n ?ri cC o r i pa re/b tn/D e bug /G ne ricCo m pa re EXEF 肃序旬301, kenshincui.25 : nlaoeif'j.SS r393 r s:hen J injuan , 22 .004,nicynxin24;Lit.Sort <>排序之后 303,shenj inJuan,22 i 丽 An 也BanieyanxinS;Odlkenshirtcui.,.25 ;三、通过自定义比较器进行排序尽管我们上面说过可以使用Sort()方法排序,但是要求

17、Student必须实现IComparable泛型接口或接口,那么我们有没有其他的方法呢?其实是有的,个人感觉这种方法多数情况下会更好一些。那就是:List.Sort ( 泛型Comparison) 和List.Sort ( 泛型IComparer) 方法。之所以将这两种重载放到一起来说,是因为二者在使用范围上很类似。首先看一下 List.Sort ( 泛型Comparison)方法,此方法的参数是Comparison 类型,其实是一个包含两个参数的委托,因此使用此方法,我们只需要定义一个委托,其两个参数均为 Student类型,在委托实现的方法比较两个Student对象的Age属性即可。田E代

18、码using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace GenericCompareclass Programstatic void Main( string args)List<Student> students= new List<Student>();students.Add(new Student( "001” , "kenshincui" , 25);students.Add(newStudent(&q

19、uot;002","miaoer" ,23);students.Add(newStudent("003","shenjinjuan",22);students.Add(newStudent("004","nieyanxin",24);Console.WriteLine("未进行排序之前:");in students)foreach (Student st (Console.WriteLine(st.No+","+st.Name+ ",&

20、quot; +st.Age+ "");Console.WriteLine("List.Sort ( 泛型 Comparison)排序之后:”);students.Sort(delegate (Student a, Student b) (reTo(b.Age); );foreach (Student st in students)(Console.WriteLine(st.No +"," + st.Name +Console.ReadKey();return a.Age.Compa+ st.Age +"");运行结果(注意此

21、时以及下面的所有例子中Student 均不需要实现IComparable泛型接口或接口): file/F:/CS h parp/G enericCompj rg/G e ne-ri cC o m pa re/b i n/D ebug /Gene ricCo e pa re EXE楂诳行排序之前:kenshirtcuiJ.25 Z102 r m 张 口已1? 23 %193 r when jin jut 律 rip 22 fi04nicynxin2-l;Li$t.Sort泛型 Conipai*3.2on> 排序之后;103, shen j ir> juan22 iMiAdttt

22、9;>23 $lanieyanxinSl;ldlJ.kenshirtcuiJ.25 ;接着我们看一下 List.Sort ( 泛型IComparer),此方法需要一个泛型IComparer 接口类型,因此只要定义一个类实现此接口然后再调用此方法即可。田E代码using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace GenericCompareclass StudentCompare :IComparer<Student>public int Compa

23、re(Student a, Student b)return a.Age.CompareTo(b.Age);=new List<Student>();Student(“001","kenshincui", 25);Student("002","miaoer" , 23);Student("003","shenjinjuan", 22);Student("004","nieyanxin" , 24);"未进行排序之前:&quo

24、t;);in students)"“+st.Name+ "," +st.Age+ """List.Sort ( 泛型 IComparer)排序之后:”);+ st.Age +"");EE1日代码using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace GenericCompareclass Programstatic void Main( string args)List<Studen

25、t> studentsstudents.Add(newstudents.Add(newstudents.Add(newstudents.Add(newConsole.WriteLine(foreach (Student st Console.WriteLine(st.No+Console.WriteLine(students.Sort(new StudentCompare();foreach (Student st in students)Console.WriteLine(st.No +"," + st.Name +Console.ReadKey();运行效果:*

26、fi le/Z/F/CS h pa rp/G enerkC ompa re/G eneri cCom pa re/b i n/D ebu /GenericCo m pa re. EXE未进行排序之既301, kenshincui.25 :D02z mlaoeir'j.SS r1433r shcn J.njnn22 f004 > n i.时叫 xin 24 :Li&t .Sort泛型I Comparer > 排序之后;383, shen j in Juan i丽 也丽4,nieyanxin,24;0dlJ.kenshirtcuiJl.25 ;四、设定排序范围虽然上面的

27、方法都实现了泛型集合排序,但是有时我们并不需要对整个集合进行排序而是指对其中一定范围内容的对象进行排序,那么我们就需要使用Sort方法的第四种重载:List.Sort (Int32, Int32,泛型IComparer)。前两个参数分别代表排序的其实位置和排序长度,最后一个参数仍然是泛型IComparer 接口类型。上面我们已经定义了StudentComparer类,实现了 IComparer 接口,这里就可以直接使用了,下面我们只对前三个学生按照年龄由小到大进行排序。田E代码using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace GenericCompareclass Programstatic void Main( string args)List<Student> students=new List<Student>();students.Add(newStudent(Sr,"kenshincui",25);students.Add(newStudent("002","miaoe

温馨提示

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

评论

0/150

提交评论