//準備資料 var BuildingList = new List<Building>(); for (int i = 0; i < 5; i++) { BuildingList.Add(new Building { Age = 1 * (i+1), Pin = 1 * (i+1), CaseDate = DateTime.Now.AddDays(i +1) }); }
//排序欄位 switch (OrderByColumn) { case OrderByColumnEnum.Pin: switch (OrderBy) { case OrderByEnum.ASC: //因為裡面用到的欄位不同,又是強型別,只能寫死... BuildingList = BuildingList.OrderBy(x => x.Pin).ToList(); break; case OrderByEnum.DESC: BuildingList = BuildingList.OrderByDescending(x => x.Pin).ToList(); break; } break; case OrderByColumnEnum.Age: switch (OrderBy) { case OrderByEnum.ASC: BuildingList = BuildingList.OrderBy(x => x.Age).ToList(); break; case OrderByEnum.DESC: BuildingList = BuildingList.OrderByDescending(x =>x.Age).ToList(); break; } break; case OrderByColumnEnum.CaseDate: switch (OrderBy) { case OrderByEnum.ASC: BuildingList = BuildingList.OrderBy(x => x.CaseDate).ToList(); break; case OrderByEnum.DESC: BuildingList = BuildingList.OrderByDescending(x => x.CaseDate).ToList(); break; } break; } BuildingList.Dump(); }
//準備資料 var BuildingList = new List<Building>(); for (int i = 0; i < 5; i++) { BuildingList.Add(new Building { Age = 1 * (i+1), Pin = 1 * (i+1), CaseDate = DateTime.Now.AddDays(i +1) }); }
//排序欄位 var param = OrderByColumnEnum.Pin.ToString();
//透過PropertyInfo操作 var propertyInfo = typeof(Building).GetProperty(param); switch (OrderBy) { case OrderByEnum.ASC: BuildingList = BuildingList.OrderBy(x => propertyInfo.GetValue(x, null)).ToList(); break; case OrderByEnum.DESC: BuildingList = BuildingList.OrderByDescending(x => propertyInfo.GetValue(x, null)).ToList(); break; }