1.开发过程中,会遇到OrderBy/OrderByDescending排序无法满足的情况,此时就需要自定义排序,按照想要的排序规则取排序,比如订单的状态等等。
2.自定义泛型比较器代码如下:
/// <summary>
/// 自定义泛型比较器(用于自定义排序)
/// </summary>
public class CustomComparer<T> : IComparer<T>
{
/// <summary>
/// 排好的排序列表
/// </summary>
private List<T> _preferenceList;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="preferenceList">排好的排序列表</param>
public CustomComparer(List<T> preferenceList)
{
_preferenceList = preferenceList ?? new List<T>();
}
/// <summary>
/// 执行比较
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public int Compare(T x, T y)
{
if (!_preferenceList.Any())
{
return DefaultCompare(x, y);
}
var index_x = _preferenceList.IndexOf(x);
var index_y = _preferenceList.IndexOf(y);
return index_x.CompareTo(index_y);
}
/// <summary>
/// 默认比较
/// </summary>
private int DefaultCompare(T x, T y)
{
return string.Compare(x.ToString(), y.ToString(), false, CultureInfo.CurrentCulture);
}
}
3.使用(此处以自定义用户名称作为数组去排序):
var users = new List<User>()
{
new User() { Id = 1,UserName = "张三",Password = "123456",Age = 18,Sex = 0},
new User() { Id = 2,UserName = "李婷婷",Password = "123456",Age = 28,Sex = 1},
new User() { Id = 3,UserName = "王五",Password = "123456",Age = 19,Sex = 0},
new User() { Id = 4,UserName = "赵灵儿",Password = "123456",Age = 21,Sex = 1},
new User() { Id = 5,UserName = "韩企",Password = "123456",Age = 22,Sex = 0},
new User() { Id = 6,UserName = "宋华",Password = "123456",Age = 20,Sex = 0},
new User() { Id = 7,UserName = "王斌",Password = "123456",Age = 21,Sex = 0}
};
var orderbys = new List<string>()
{
"李婷婷","赵灵儿","张三","王五","韩企","宋华","王斌"
};
var result = users.AsQueryable().OrderByDescending(s=>s.UserName, new CustomComparer<string>(orderbys));
4.结果展示: