List 排序

来源:互联网 发布:数据透视经典显示 编辑:程序博客网 时间:2024/05/17 05:17
//list排序
    private List<PreDistribution> ListSort(string field, string rule, List<PreDistribution> list)
    {
        if (!string.IsNullOrEmpty(rule) && (rule.ToLower().Equals("desc") || rule.ToLower().Equals("asc")))
        {
            try
            {
                List<PreDistribution> infoList = list;
                infoList.Sort(
                    delegate(PreDistribution info1, PreDistribution info2)
                    {
                        System.Type t = typeof(PreDistribution);
                        PropertyInfo pro = t.GetProperty(field);
                        return rule.ToLower().Equals("asc") ?
                            pro.GetValue(info1, null).ToString().CompareTo(pro.GetValue(info2, null).ToString()) :
                            pro.GetValue(info2, null).ToString().CompareTo(pro.GetValue(info1, null).ToString());
                    });
            }
            catch (Exception ex)
            {
                return list;
            }
        }
        else
            Console.WriteLine("ruls is wrong");
        return list;

    }

filed排序字段

rule排序规则:asc or desc

list需要排序的集合

ListSort(field, rule, List<PreDistribution> list);