按值对枚举成员排序 [英] Order Enum Members by their values

查看:117
本文介绍了按值对枚举成员排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨.
如何按其值订购枚举成员?
例如我有这个枚举:

Hi .
how i can Order enum members by their values ?
for example i have this enum :

public static enum ePersianNumbersliteral
   {
       Zero = "\u0660",
       One = "\u0661",
       Two = "\u0662",
       Three = "\u0663",
       Four = "\u0664",
       Five = "\u0665",
       Six = "\u0666",
       Seven = "\u0667",
       Eight = "\u0668",
       Nine = "\u0669"
   }


现在当我使用这种类型的成员是无序的.确实按字母顺序排序!
八个
...
..
.
我希望按值订购成员!


now when i use this type members are unordered . Indeed ordered by alphabetic!
Eight
...
..
.
i want order members by value!

推荐答案

本文对一个枚举进行排序-
This article sorts an enum - Fill Combobox With Sorted Enum Without Code[^].


尝试以下方法:

Try this:

public enum ePersianNumbersliteral
{
    Zero = '\u0660',
    One = '\u0661',
    Two = '\u0662',
    Three = '\u0663',
    Four = '\u0664',
    Five = '\u0665',
    Six = '\u0666',
    Seven = '\u0667',
    Eight = '\u0668',
    Nine = '\u0669'
}





public static IEnumerable<T> SortEnumByValue<T>()
{
    return from e in Enum.GetValues(typeof(T)).Cast<T>()
           orderby e
           select e;
}
public static IEnumerable<T> SortEnumByName<T>()
{
    return from e in Enum.GetValues(typeof(T)).Cast<T>()
           let nm = e.ToString()
           orderby nm
           select e;
}





Console.WriteLine("{0}",
     string.Join(", ", SortEnumByValue<ePersianNumbersliteral>()));
Console.WriteLine("{0}",
     string.Join(", ", SortEnumByName<ePersianNumbersliteral>()));



输出为:



The output is:

Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine
Eight, Five, Four, Nine, One, Seven, Six, Three, Two, Zero


如果您真的希望intellisense列出值序列中的枚举,则该值也必须在名称中可见,以便intellisense通过对值按字母顺序排列.例如

If you *really* want intellisense to list the enums in a value sequence, that value has to be visible in the name as well so that intellisense sorts them properly by sorting the values alphabetically. E.g.

public enum ePersianNumbersliteral
{
    E0_Zero = '\u0660',
    E1_One = '\u0661',
    E2_Two = '\u0662',
    E3_Three = '\u0663',
    E4_Four = '\u0664',
    E5_Five = '\u0665',
    E6_Six = '\u0666',
    E7_Seven = '\u0667',
    E8_Eight = '\u0668',
    E9_Nine = '\u0669'
}



不是我喜欢这样.我从来没有想过要有智能感知来按值对枚举进行排序……我的枚举通常隐藏了它们所代表的值,因此,排序是任意的-为什么不将最常用的枚举放在最前面呢? ;-)

这是一种在欺骗您;-)



Not that I like this. I never had the whish to have intellisense sort the enums by value, though... My enums in general hide the value they stand for and therefore, the sorting is kind of arbitrary - why not having on top the most often used one? ;-)

This is a solution to trick intellisense when it tricks you ;-)


这篇关于按值对枚举成员排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆