新聞中心
從個(gè)小例子開(kāi)始:

創(chuàng)新互聯(lián)公司是一家網(wǎng)站建設(shè)、成都做網(wǎng)站,提供網(wǎng)頁(yè)設(shè)計(jì),網(wǎng)站設(shè)計(jì),網(wǎng)站制作,建網(wǎng)站,按需開(kāi)發(fā),網(wǎng)站開(kāi)發(fā)公司,于2013年成立是互聯(lián)行業(yè)建設(shè)者,服務(wù)者。以提升客戶品牌價(jià)值為核心業(yè)務(wù),全程參與項(xiàng)目的網(wǎng)站策劃設(shè)計(jì)制作,前端開(kāi)發(fā),后臺(tái)程序制作以及后期項(xiàng)目運(yùn)營(yíng)并提出專業(yè)建議和思路。
- int[] intArray = new int[]{2,3,6,1,4,5};
- Array.Sort(intArray);
- Array.ForEach
(intArray,(i)=>Console.WriteLine(i));
這個(gè)例子定義了一個(gè)int數(shù)組,然后使用Array.Sort(arr)靜態(tài)方法對(duì)此數(shù)組進(jìn)行排序,最后輸出排序后的數(shù)組。以上例子將毫無(wú)意外的依次輸出1,2,3,4,5,6.
為什么Array的Sort方法可以正確的對(duì)int數(shù)組進(jìn)行排序呢,我們自定義類可以嗎?試試看,如下代碼:
- public class Student
- {
- public int Age { get; set; }
- public string Name { get; set; }
- public int Score { get; set; }
- }
- static void Main(string[] args)
- {
- Student[] students = new Student[]{
- new Student(){Age = 10,Name="張三",Score=70},
- new Student(){Age = 12,Name="李四",Score=97},
- new Student(){Age = 11,Name="王五",Score=80},
- new Student(){Age = 9,Name="趙六",Score=66},
- new Student(){Age = 12,Name="司馬",Score=90},
- };
- Console.WriteLine("--------------默認(rèn)排序輸出--------");
- Array.Sort(students);
- Array.ForEach
(students,(s)=>Console.WriteLine(string.Format("{0}{1,2}歲了,他的分?jǐn)?shù)是{2,3}",s.Name,s.Age,s.Score))); - Console.Read();
- }
我們定義了Student類然后同樣對(duì)他的數(shù)組進(jìn)行排序,程序正確的編譯通過(guò),但是運(yùn)行出錯(cuò),運(yùn)行時(shí)拋出了異常:System.InvalidOperationException{"Failed to compare two elements in the array."},這個(gè)異常的InnerException是ArgumentException{"At least one object must implement IComparable."};運(yùn)行時(shí)異常說(shuō)明:我們要使用Array.Sort(arr)靜態(tài)方法,必須得保證數(shù)組中有一個(gè)元素實(shí)現(xiàn)IComparable接口。既然如此我們就讓Student類實(shí)現(xiàn)IComparable接口.
- public class Student :IComparable
- {
- public int Age { get; set; }
- public string Name { get; set; }
- public int Score { get; set; }
- ///
- /// 實(shí)現(xiàn)IComparable接口,用Age做比較
- ///
- /// 比較對(duì)象
- ///
比較結(jié)果 - public int CompareTo(object obj)
- {
- if (obj is Student)
- {
- return Age.CompareTo(((Student)obj).Age);
- }
- return 1;
- }
- }
在Student類中實(shí)現(xiàn)了IComparable接口,在CompareTo方法中比較Student的Age屬性,這一次再次編譯運(yùn)行,程序正常的輸出了按照年齡排序的Student數(shù)組。
假如說(shuō)我們要對(duì)Student的Score屬性進(jìn)行排序該怎么辦呢? Student類實(shí)現(xiàn)的IComparable接口只能按照一種屬性排序呀。
這個(gè)是很容易實(shí)現(xiàn)的.net的類庫(kù)開(kāi)發(fā)者早為我們準(zhǔn)備了另一個(gè)接口IComparer
- public class StudentScoreComparer : IComparer
- {
- public int Compare(Student x, Student y)
- {
- return x.Score.CompareTo(y.Score);
- }
- }
現(xiàn)在我們可以使用下面代碼對(duì)Student數(shù)組按照Score屬性進(jìn)行排序:
Console.WriteLine("----------按分?jǐn)?shù)排序輸出------------");
Array.Sort(students, new StudentScoreComparer());
Array.ForEach
不過(guò)一個(gè)簡(jiǎn)單的按照Score屬性排序,再定義一個(gè)類是不是有點(diǎn)大題小作呀,有沒(méi)有更好的辦法呢?當(dāng)然有. .net為我們準(zhǔn)備了比較對(duì)象大小的委托Comparison
- Console.WriteLine("----------按分?jǐn)?shù)排序輸出----------");
- Array.Sort(students, (s1, s2) => s1.Score.CompareTo(s2.Score));
- Array.ForEach
(students, (s) => Console.WriteLine(string.Format("{0}{1,2}歲了,他的分?jǐn)?shù)是{2,3}", s.Name, s.Age, s.Score)));
完整代碼示例如下:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace SortingInCSharp
- {
- class Program
- {
- public class Student : IComparable
- {
- public int Age { get; set; }
- public string Name { get; set; }
- public int Score { get; set; }
- ///
- /// 實(shí)現(xiàn)IComparable接口,用Age做比較
- ///
- /// 比較對(duì)象
- ///
比較結(jié)果 - public int CompareTo(object obj)
- {
- if (obj is Student)
- {
- return Age.CompareTo(((Student)obj).Age);
- }
- return 1;
- }
- }
- static void Main(string[] args)
- {
- Student[] students = new Student[]{
- new Student(){Age = 10,Name="張三",Score=70},
- new Student(){Age = 12,Name="李四",Score=97},
- new Student(){Age = 11,Name="王五",Score=80},
- new Student(){Age = 9,Name="趙六",Score=66},
- new Student(){Age = 12,Name="司馬",Score=90},
- };
- Console.WriteLine("--------------默認(rèn)排序輸出--------");
- Array.Sort(students);
- Array.ForEach
(students, (s) => Console.WriteLine(string.Format("{0}{1,2}歲了,他的分?jǐn)?shù)是{2,3}", s.Name, s.Age, s.Score))); - Console.WriteLine("----------按分?jǐn)?shù)排序輸出------------");
- Array.Sort(students, new StudentScoreComparer());
- Array.ForEach
(students, (s) => Console.WriteLine(string.Format("{0}{1,2}歲了,他的分?jǐn)?shù)是{2,3}", s.Name, s.Age, s.Score))); - Console.WriteLine("----------按分?jǐn)?shù)排序輸出----------");
- Array.Sort(students, (s1, s2) => s1.Score.CompareTo(s2.Score));
- Array.ForEach
(students, (s) => Console.WriteLine(string.Format("{0}{1,2}歲了,他的分?jǐn)?shù)是{2,3}", s.Name, s.Age, s.Score))); - Console.Read();
- }
- public class StudentScoreComparer : IComparer
- {
- public int Compare(Student x, Student y)
- {
- return x.Score.CompareTo(y.Score);
- }
- }
- }
- }
總結(jié):
在C#中有三個(gè)關(guān)于比較對(duì)象大小的接口,分別是IComparable、IComparable
原文鏈接:http://www.cnblogs.com/yukaizhao/archive/2011/08/19/csharp-compare.html
【責(zé)任編輯:彭凡 TEL:(010)68476606】
網(wǎng)站名稱:C#數(shù)組排序與對(duì)象大小比較
轉(zhuǎn)載來(lái)源:http://fisionsoft.com.cn/article/cdpjedg.html


咨詢
建站咨詢
