C#基礎(chǔ)之?dāng)?shù)組排序、對(duì)象大小比較實(shí)現(xiàn)代碼
更新時(shí)間:2011年08月27日 00:14:06 作者:
C#基礎(chǔ)之?dāng)?shù)組排序、對(duì)象大小比較實(shí)現(xiàn)代碼,學(xué)習(xí)c#的朋友可以參考下。
從個(gè)小例子開(kāi)始:
int[] intArray = new int[]{2,3,6,1,4,5};
Array.Sort(intArray);
Array.ForEach<int>(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)行排序呢,我們自定義類(lèi)可以嗎?試試看,如下代碼:
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<Student>(students,(s)=>Console.WriteLine(string.Format("{0}{1,2}歲了,他的分?jǐn)?shù)是{2,3}",s.Name,s.Age,s.Score)));
Console.Read();
}
我們定義了Student類(lèi)然后同樣對(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類(lèi)實(shí)現(xiàn)IComparable接口.
public class Student :IComparable
{
public int Age { get; set; }
public string Name { get; set; }
public int Score { get; set; }
/// <summary>
/// 實(shí)現(xiàn)IComparable接口,用Age做比較
/// </summary>
/// <param name="obj">比較對(duì)象</param>
/// <returns>比較結(jié)果</returns>
public int CompareTo(object obj)
{
if (obj is Student)
{
return Age.CompareTo(((Student)obj).Age);
}
return 1;
}
}
在Student類(lèi)中實(shí)現(xiàn)了IComparable接口,在CompareTo方法中比較Student的Age屬性,這一次再次編譯運(yùn)行,程序正常的輸出了按照年齡排序的Student數(shù)組。
假如說(shuō)我們要對(duì)Student的Score屬性進(jìn)行排序該怎么辦呢? Student類(lèi)實(shí)現(xiàn)的IComparable接口只能按照一種屬性排序呀。
這個(gè)是很容易實(shí)現(xiàn)的.net的類(lèi)庫(kù)開(kāi)發(fā)者早為我們準(zhǔn)備了另一個(gè)接口IComparer<T>接口用來(lái)實(shí)現(xiàn)比較類(lèi)型T的兩個(gè)實(shí)例。如下StudentScoreComparer類(lèi)實(shí)現(xiàn)了對(duì)Student按照Score屬性比較的IComparer<Student>
public class StudentScoreComparer : IComparer<Student>
{
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<Student>(students, (s) => Console.WriteLine(string.Format("{0}{1,2}歲了,他的分?jǐn)?shù)是{2,3}", s.Name, s.Age, s.Score)));
不過(guò)一個(gè)簡(jiǎn)單的按照Score屬性排序,再定義一個(gè)類(lèi)是不是有點(diǎn)大題小作呀,有沒(méi)有更好的辦法呢?當(dāng)然有. .net為我們準(zhǔn)備了比較對(duì)象大小的委托Comparison<T>我們可以使用拉姆達(dá)表達(dá)式或者匿名委托直接排序,如下代碼實(shí)現(xiàn):
Console.WriteLine("----------按分?jǐn)?shù)排序輸出----------");
Array.Sort(students, (s1, s2) => s1.Score.CompareTo(s2.Score));
Array.ForEach<Student>(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; }
/// <summary>
/// 實(shí)現(xiàn)IComparable接口,用Age做比較
/// </summary>
/// <param name="obj">比較對(duì)象</param>
/// <returns>比較結(jié)果</returns>
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<Student>(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<Student>(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<Student>(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<Student>
{
public int Compare(Student x, Student y)
{
return x.Score.CompareTo(y.Score);
}
}
}
}
總結(jié):
在C#中有三個(gè)關(guān)于比較對(duì)象大小的接口,分別是IComparable、IComparable<T>和IComparer<T>。 IComparable和IComparable<T>是類(lèi)本身實(shí)現(xiàn)的在實(shí)例之間比較大小的行為定義。IComparer<T>是定義在被比較類(lèi)之外的專(zhuān)門(mén)比較兩個(gè)T類(lèi)型對(duì)象大小的行為,另外還有一個(gè)用于比較的委托定義Comparison<T>可以讓我們用拉姆達(dá)表達(dá)式或者匿名委托或方法更方便的排序。
復(fù)制代碼 代碼如下:
int[] intArray = new int[]{2,3,6,1,4,5};
Array.Sort(intArray);
Array.ForEach<int>(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)行排序呢,我們自定義類(lèi)可以嗎?試試看,如下代碼:
復(fù)制代碼 代碼如下:
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<Student>(students,(s)=>Console.WriteLine(string.Format("{0}{1,2}歲了,他的分?jǐn)?shù)是{2,3}",s.Name,s.Age,s.Score)));
Console.Read();
}
我們定義了Student類(lèi)然后同樣對(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類(lèi)實(shí)現(xiàn)IComparable接口.
復(fù)制代碼 代碼如下:
public class Student :IComparable
{
public int Age { get; set; }
public string Name { get; set; }
public int Score { get; set; }
/// <summary>
/// 實(shí)現(xiàn)IComparable接口,用Age做比較
/// </summary>
/// <param name="obj">比較對(duì)象</param>
/// <returns>比較結(jié)果</returns>
public int CompareTo(object obj)
{
if (obj is Student)
{
return Age.CompareTo(((Student)obj).Age);
}
return 1;
}
}
在Student類(lèi)中實(shí)現(xiàn)了IComparable接口,在CompareTo方法中比較Student的Age屬性,這一次再次編譯運(yùn)行,程序正常的輸出了按照年齡排序的Student數(shù)組。
假如說(shuō)我們要對(duì)Student的Score屬性進(jìn)行排序該怎么辦呢? Student類(lèi)實(shí)現(xiàn)的IComparable接口只能按照一種屬性排序呀。
這個(gè)是很容易實(shí)現(xiàn)的.net的類(lèi)庫(kù)開(kāi)發(fā)者早為我們準(zhǔn)備了另一個(gè)接口IComparer<T>接口用來(lái)實(shí)現(xiàn)比較類(lèi)型T的兩個(gè)實(shí)例。如下StudentScoreComparer類(lèi)實(shí)現(xiàn)了對(duì)Student按照Score屬性比較的IComparer<Student>
復(fù)制代碼 代碼如下:
public class StudentScoreComparer : IComparer<Student>
{
public int Compare(Student x, Student y)
{
return x.Score.CompareTo(y.Score);
}
}
現(xiàn)在我們可以使用下面代碼對(duì)Student數(shù)組按照Score屬性進(jìn)行排序:
復(fù)制代碼 代碼如下:
Console.WriteLine("----------按分?jǐn)?shù)排序輸出------------");
Array.Sort(students, new StudentScoreComparer());
Array.ForEach<Student>(students, (s) => Console.WriteLine(string.Format("{0}{1,2}歲了,他的分?jǐn)?shù)是{2,3}", s.Name, s.Age, s.Score)));
不過(guò)一個(gè)簡(jiǎn)單的按照Score屬性排序,再定義一個(gè)類(lèi)是不是有點(diǎn)大題小作呀,有沒(méi)有更好的辦法呢?當(dāng)然有. .net為我們準(zhǔn)備了比較對(duì)象大小的委托Comparison<T>我們可以使用拉姆達(dá)表達(dá)式或者匿名委托直接排序,如下代碼實(shí)現(xiàn):
復(fù)制代碼 代碼如下:
Console.WriteLine("----------按分?jǐn)?shù)排序輸出----------");
Array.Sort(students, (s1, s2) => s1.Score.CompareTo(s2.Score));
Array.ForEach<Student>(students, (s) => Console.WriteLine(string.Format("{0}{1,2}歲了,他的分?jǐn)?shù)是{2,3}", s.Name, s.Age, s.Score)));
完整代碼示例如下:
復(fù)制代碼 代碼如下:
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; }
/// <summary>
/// 實(shí)現(xiàn)IComparable接口,用Age做比較
/// </summary>
/// <param name="obj">比較對(duì)象</param>
/// <returns>比較結(jié)果</returns>
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<Student>(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<Student>(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<Student>(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<Student>
{
public int Compare(Student x, Student y)
{
return x.Score.CompareTo(y.Score);
}
}
}
}
總結(jié):
在C#中有三個(gè)關(guān)于比較對(duì)象大小的接口,分別是IComparable、IComparable<T>和IComparer<T>。 IComparable和IComparable<T>是類(lèi)本身實(shí)現(xiàn)的在實(shí)例之間比較大小的行為定義。IComparer<T>是定義在被比較類(lèi)之外的專(zhuān)門(mén)比較兩個(gè)T類(lèi)型對(duì)象大小的行為,另外還有一個(gè)用于比較的委托定義Comparison<T>可以讓我們用拉姆達(dá)表達(dá)式或者匿名委托或方法更方便的排序。
您可能感興趣的文章:
- C#二維數(shù)組基本用法實(shí)例
- C#使用foreach語(yǔ)句遍歷二維數(shù)組的方法
- C#實(shí)現(xiàn)對(duì)二維數(shù)組排序的方法
- c#基礎(chǔ)之?dāng)?shù)組與接口使用示例(遍歷數(shù)組 二維數(shù)組)
- C#數(shù)組排序的兩種常用方法
- C# 數(shù)組查找與排序?qū)崿F(xiàn)代碼
- C#實(shí)現(xiàn)對(duì)數(shù)組進(jìn)行隨機(jī)排序類(lèi)實(shí)例
- C#使用linq對(duì)數(shù)組進(jìn)行篩選排序的方法
- C#數(shù)組反轉(zhuǎn)與排序?qū)嵗治?/a>
- C#實(shí)現(xiàn)的二維數(shù)組排序算法示例
相關(guān)文章
C#中DataTable排序、檢索、合并等操作實(shí)例
這篇文章主要介紹了C#中DataTable排序、檢索、合并等操作實(shí)例,其中詳細(xì)介紹了DataTable.Select的一些注意問(wèn)題和使用技巧等,需要的朋友可以參考下2014-04-04C#?winform跨線程操作控件的實(shí)現(xiàn)
本文主要介紹了C#?winform跨線程操作控件的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06Unity UGUI通過(guò)搖桿控制角色移動(dòng)
這篇文章主要為大家詳細(xì)介紹了Unity3D基于陀螺儀實(shí)現(xiàn)VR相機(jī)功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-11-11C#使用CryptoStream類(lèi)加密和解密字符串的實(shí)現(xiàn)
CryptoStream設(shè)計(jì)用于在內(nèi)容以流的形式輸出到文件時(shí)加密和解密內(nèi)容,本文主要介紹了C#使用CryptoStream類(lèi)加密和解密字符串的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2024-01-01.NET/C#實(shí)現(xiàn)識(shí)別用戶訪問(wèn)設(shè)備的方法
這篇文章主要介紹了.NET/C#實(shí)現(xiàn)識(shí)別用戶訪問(wèn)設(shè)備的方法,結(jié)合實(shí)例形式分析了C#識(shí)別用戶訪問(wèn)設(shè)備的操作技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2017-02-02C#如何實(shí)現(xiàn)調(diào)取釘釘考勤接口的功能
這篇文章主要介紹了C#如何實(shí)現(xiàn)調(diào)取釘釘考勤接口的功能,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08C#與C++?dll之間傳遞字符串string?wchar_t*?char*?IntPtr問(wèn)題
C#與C++?dll之間傳遞字符串string?wchar_t*?char*?IntPtr問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11