0
点赞
收藏
分享

微信扫一扫

工作中的问题~按着枚举类型的字段进行排序

如果一个类中,有一个属性的类型是枚举型,那么,如果我们建立了一个类的集合对象,如List<类>,那我要根据它枚举值进行排序,如何进行?

事实上.net把枚举和整型自动给我们进行了一个转换,如果要排序枚举,我们可以理解成排序整型字段,没有任何分别,如果枚举没有赋值,那么.net 运行时会根据枚举元素出现的顺序进行排序,第1个元素的值为0,依次向下加1

看这个实例代码:

enum

}enum Example
{
hihi ,
ok ,
yes ,
good ,
bad ,
}
class exam
{
public Example Example { get; set; }
}

赋值并排序,然后输出:

   List<exam> e = new List<exam>();
foreach (string i in Enum.GetNames(typeof(Example)))
e.Add(new exam { Example = (Example)Enum.Parse(typeof(Example), i) });

e = e.AsQueryable().OrderByDescending(i => i.Example).ToList();

e.ForEach(i => { Console.WriteLine("枚举名称是:{0}它的值是:{1}",i.Example,(int)i.Example); });

foreach (string i in Enum.GetNames(typeof(Example)))


作者:仓储大叔,张占岭,
荣誉:微软MVP


举报

相关推荐

0 条评论