enum Enum to dictionary dictionary

Source: Internet
Author: User

Method One:
Dictionary<int, string> mydic = new Dictionary<int, string> (); foreach (Enumname foo in enum.getvalues (typeof (Enumname))) {    mydic. ADD ((int) foo, foo. ToString ());}
Method Two:
var dict = enum.getvalues (typeof (Enumname))               . Cast<enumname> ()               . ToDictionary (t = = (int) T, t = = t.tostring ());
Method Three "key is Value,value is description (if not present description is name)":
<summary>///enumeration to dictionary collection///</summary>///<typeparam name= "T" > Enum class name </typeparam>///<param Name= "Keydefault" > Default key value </param>///<param name= "Valuedefault" > Default value Value </param>///< Returns> returns the generated dictionary collection </returns>public static dictionary<string, object> enumlistdic<t> (string Keydefault, String valuedefault = "") {dictionary<string, object> dicenum = new dictionary<string, object> (    );    Type enumtype = typeof (T);    if (!enumtype.isenum) {return dicenum; } if (!string.    IsNullOrEmpty (Keydefault))//Determine whether to add the default option {Dicenum.add (Keydefault, Valuedefault); } string[] Fieldstrs = Enum.getnames (enumtype); Gets an enumeration field array of foreach (var item in fieldstrs) {string description = string.        Empty;        var field = Enumtype.getfield (item); object[] arr = field. GetCustomAttributes (typeof (DescriptionAttribute), true); Gets an array of attribute fields if (arr! = null && arr.      Length > 0)  {Description = ((DescriptionAttribute) arr[0]).   Description;  Property Description} else {description = Item;  Description does not exist fetch field name} dicenum.add (description, (int) enum.parse (enumtype, item)); The reason for not using the enumerated value value as the Dictionary key value from the enumeration example can be seen, in fact, this should be judged that his value does not exist, the default field name} return dicenum;}

  

enum Enum to dictionary dictionary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.