#引言
有一個集合,對其進行排序,排序規則為:按對象中某個字段的特定順序進行排序,比如:對象屬性id,按照【4,2,5,1】的順序排序;
#代碼:
1 public class Foo 2 { 3 public int Id { get; set; } 4 public string Name { get; set; } 5 }
1、demo1:按字段id進行自定義排序
1 List<Foo> foos = new List<Foo> { 2 new Foo { Id = 1, Name = "b" }, new Foo { Id = 2, Name = "a" }, 3 new Foo { Id = 3, Name = "A" }, new Foo { Id = 4, Name = "B" } 4 }; 5 int[] orderArr = new int[]{4,2,3,1}; 6 foos = foos.OrderBy(e => 7 { 8 var index = 0; 9 index = Array.IndexOf(orderArr, e.Id); 10 if (index != -1) { return index; } 11 else 12 { 13 return int.MaxValue; 14 } 15 16 }).ToList(); 17 18 foos.ForEach(p => 19 { 20 Console.WriteLine(string.Format("Id:{0},Name:{1}",p.Id,p.Name)); 21 });
——————————————————————————————————————————————————————————————————