C#自定义类的集合 排序问题
项目需求 一个自定义类,根据id 升序。
上代码:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 var sl = GetS(); 6 sl.Sort(new Comparison<SItem>((x, y) => 7 { 8 return x.ComString(y); //使用扩展方法 9 } 10 )); 11 12 13 foreach (var item in sl) 14 { 15 Console.WriteLine(item.Id+" "+item.Size+" "+item.SKU); 16 } 17 } 18 19 public static List<SItem> GetS() 20 { 21 var temp = new List<SItem>(); 22 temp.Add(new SItem { Id = "002", Size = 2, SKU = "Test" }); 23 temp.Add(new SItem { Id = "001", Size = 2, SKU = "Test" }); 24 temp.Add(new SItem { Id = "003", Size = 2, SKU = "Test" }); 25 temp.Add(new SItem { Id = "002", Size = 2, SKU = "Test" }); 26 return temp; 27 } 28 } 29 30 31 class SItem 32 { 33 public string Id { get; set; } 34 public string SKU { get; set; } 35 public int? Size { get; set; } 36 } 37 38 static class Linq 39 { 40 static public int ComString(this SItem s,SItem t) 41 { 42 var a = s.Id; 43 var b = t.Id; 44 if (a.Length!=b.Length) 45 { 46 if (a.Length>b.Length) 47 { 48 return 1; 49 } 50 else 51 { 52 return -1; 53 } 54 } 55 for (int i = 0; i < a.Length; i++) 56 { 57 if (a[i]>b[i]) 58 { 59 return 1; 60 } 61 if (a[i]<b[i]) 62 { 63 return -1; 64 } 65 } 66 return 0; 67 } 68 }