c#自定义类的指定字段排序
生活随笔
收集整理的這篇文章主要介紹了
c#自定义类的指定字段排序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
類Chair的定義代碼如下:
public class Chair {public double myPrice;public string myVendor, myID;public Chair() { }public Chair(double price, string vendor, string sku){myPrice = price;myVendor = vendor;myID = sku;} }要求通過調用Array.Sort方法對Chair 對象數組按myID的unicode碼值進行由大到小排序。
//通過調用Array.Sort方法對Chair對象數組按myID的unicode碼值進行由大到小排序using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace ConsoleApp6 {class Chair : IComparable{public double myPrice;public string myVendor, myID;public Chair() { }public Chair(double price, string vendor, string id){myPrice = price;myVendor = vendor;myID = id;}int IComparable.CompareTo(Object obj){if (obj is Chair){Chair castObj = (Chair)obj;if ((string.CompareOrdinal(this.myID,castObj.myID) < 0)) return 1;else if ((string.CompareOrdinal(this.myID, castObj.myID)) > 0) return -1;else return 0;}throw new ArgumentException("object is not a Chair");}}class Program{static void Main(string[] args){Chair[] chairs = new Chair[4];chairs[0] = new Chair(150.0, "gdne", "9988");chairs[1] = new Chair(250.0, "Lan", "w");chairs[2] = new Chair(100.0, "lne", "漢");chairs[3] = new Chair(120.0, "Harris", "939");Array.Sort(chairs);foreach (Chair c in chairs){Console.WriteLine(c.myPrice + " " + c.myVendor + " " + c.myID);}}} }總結
以上是生活随笔為你收集整理的c#自定义类的指定字段排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 全息摄影
- 下一篇: 学生信息管理系统(C语言,带文件操作)