C#通過IComparable實(shí)現(xiàn)ListT.sort()排序
本文實(shí)例講述了C#通過IComparable實(shí)現(xiàn)ListT.sort()排序的方法,分享給大家供大家參考之用。具體方法如下:
通常來說,List<T>.sort()可以實(shí)現(xiàn)對(duì)T的排序,比如List<int>.sort()執(zhí)行后集合會(huì)按照int從小到大排序。如果T是一個(gè)自定義的Object,可是我們想按照自己的方式來排序,那該怎么辦呢,其實(shí)可以用過IComparable接口重寫CompareTo方法來實(shí)現(xiàn)。流程如下:
一、第一步我們申明一個(gè)類Person但是要繼承IComparable接口:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestIComparable
{
public class Person : IComparable<Person>
{
public string Name { get; set; }
public int Age { get; set; }
public int CompareTo(Person obj)
{
int result;
if (this.Name == obj.Name && this.Age == obj.Age)
{
result = 0;
}
else
{
if (this.Name.CompareTo(obj.Name) > 0)
{
result = 1;
}
else if (this.Name == obj.Name && this.Age > obj.Age)
{
result = 1;
}
else
{
result = -1;
}
}
return result;
}
public override string ToString()
{
return this.Name + "-" + this.Age;
}
}
}
二、然后在主函數(shù)里面調(diào)用sort方法即可.類就會(huì)按照姓名從小到大,如果姓名相同則按照年齡從小到大排序了。
public class Program
{
public static void Main(string[] args)
{
List<Person> lstPerson = new List<Person>();
lstPerson.Add(new Person(){ Name="Bob",Age=19});
lstPerson.Add(new Person(){ Name="Mary",Age=18});
lstPerson.Add(new Person() { Name = "Mary", Age = 17 });
lstPerson.Add(new Person(){ Name="Lily",Age=20});
lstPerson.Sort();
Console.ReadKey();
}
}
三、如果不繼承IComparable接口,我們該如何實(shí)現(xiàn)排序呢??梢允褂肔inq來實(shí)現(xiàn)。其實(shí)效果是一樣的,只是如果類的集合要經(jīng)常排序的話,建議使用繼承接口的方法,這樣可以簡化sort的代碼,而且更容易讓人看懂。
public static void Main(string[] args)
{
List<Person> lstPerson = new List<Person>();
lstPerson.Add(new Person(){ Name="Bob",Age=19});
lstPerson.Add(new Person(){ Name="Mary",Age=18});
lstPerson.Add(new Person() { Name = "Mary", Age = 17 });
lstPerson.Add(new Person(){ Name="Lily",Age=20});
lstPerson.Sort((x,y) =>
{
int result;
if (x.Name == y.Name && x.Age == y.Age)
{
result = 0;
}
else
{
if (x.Name.CompareTo(y.Name) > 0)
{
result = 1;
}
else if (x.Name == y.Name && x.Age > y.Age)
{
result = 1;
}
else
{
result = -1;
}
}
return result;
});
Console.ReadKey();
}
希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
C#實(shí)現(xiàn)在PDF文檔中應(yīng)用多種不同字體
在PDF文檔中,可繪制不同字體樣式、不同語言的文字,可通過使用Standard字體、TrueType字體、CJK字體或者自定義(私有)等字體類型。本文將具體介紹實(shí)現(xiàn)的方法,需要的可以參考一下2022-01-01
Unity實(shí)現(xiàn)車型識(shí)別的示例代碼
這篇文章主要介紹了在Unity中接入百度AI,實(shí)現(xiàn)檢測一張車輛圖片的具體車型。即對(duì)于輸入的一張圖片(可正常解碼,且長寬比適宜),輸出圖片的車輛品牌及型號(hào)。需要的可以參考一下2022-01-01
WPF/Silverlight實(shí)現(xiàn)圖片局部放大的方法分析
這篇文章主要介紹了WPF/Silverlight實(shí)現(xiàn)圖片局部放大的方法,結(jié)合實(shí)例形式分析了WPF/Silverlight針對(duì)圖片屬性操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-03-03
C#實(shí)現(xiàn)基于任務(wù)的異步編程模式
本文詳細(xì)講解了C#實(shí)現(xiàn)基于任務(wù)的異步編程模式,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-04-04
C# Winform 禁止用戶調(diào)整ListView的列寬
在使用 ListView 的時(shí)候, 有時(shí)我們不想讓別人隨意調(diào)整列寬, 或者某幾列的列寬, 以便達(dá)到美觀, 或者隱藏?cái)?shù)據(jù)的作用. 那么可以用一下代碼來實(shí)現(xiàn)2011-05-05

