Перечислить в словарь в C # - PullRequest
51 голосов
/ 07 апреля 2011

Я искал это онлайн, но не могу найти ответ, который ищу.

В основном у меня есть следующее перечисление:

public enum typFoo : int
{
   itemA : 1,
   itemB : 2
   itemC : 3
}

Как я могу преобразовать это перечисление в словарь, чтобы оно сохранялось в следующем словаре?

Dictionary<int,string> mydic = new Dictionary<int,string>();

И mydic будет выглядеть так:

1, itemA
2, itemB
3, itemC

Есть идеи?

Ответы [ 11 ]

140 голосов
/ 07 апреля 2011

Попробуйте:

var dict = Enum.GetValues(typeof(typFoo))
               .Cast<typFoo>()
               .ToDictionary(t => (int)t, t => t.ToString() );
43 голосов
/ 07 апреля 2011

См .: Как мне перечислить перечисление в C #?

foreach( typFoo foo in Enum.GetValues(typeof(typFoo)) )
{
    mydic.Add((int)foo, foo.ToString());
}
13 голосов
/ 23 января 2015

Адаптация Ответ Ани , чтобы его можно было использовать как универсальный метод (спасибо, toddmo ):

public static Dictionary<int, string> EnumDictionary<T>()
{
    if (!typeof(T).IsEnum)
        throw new ArgumentException("Type must be an enum");
    return Enum.GetValues(typeof(T))
        .Cast<T>()
        .ToDictionary(t => (int)(object)t, t => t.ToString());
}
5 голосов
/ 15 мая 2017
  • Метод расширения
  • Обычные имена
  • Одна строка
  • C # 7 возвращает синтаксис (но вы можете использовать скобки в тех старых унаследованных версиях C #)
  • Выдает ArgumentException, если тип не System.Enum, благодаря Enum.GetValues
  • IntelliSense будет ограничен структурами (ограничение enum пока недоступно)
  • Позволяет при необходимости использовать enum для индексации в словаре.
public static Dictionary<T, string> ToDictionary<T>() where T : struct
  => Enum.GetValues(typeof(T)).Cast<T>().ToDictionary(e => e, e => e.ToString());
5 голосов
/ 23 июля 2016

Использование:

public static class EnumHelper
{
    public static IDictionary<int, string> ConvertToDictionary<T>() where T : struct
    {
        var dictionary = new Dictionary<int, string>();

        var values = Enum.GetValues(typeof(T));

        foreach (var value in values)
        {
            int key = (int) value;

            dictionary.Add(key, value.ToString());
        }

        return dictionary;
    }
}

Использование:

public enum typFoo : int
{
   itemA = 1,
   itemB = 2,
   itemC = 3
}

var mydic = EnumHelper.ConvertToDictionary<typFoo>();
3 голосов
/ 26 июля 2018

Другой метод расширения, основанный на примере Арифмоманика :

    /// <summary>
    /// Returns a Dictionary&lt;int, string&gt; of the parent enumeration. Note that the extension method must
    /// be called with one of the enumeration values, it does not matter which one is used.
    /// Sample call: var myDictionary = StringComparison.Ordinal.ToDictionary().
    /// </summary>
    /// <param name="enumValue">An enumeration value (e.g. StringComparison.Ordianal).</param>
    /// <returns>Dictionary with Key = enumeration numbers and Value = associated text.</returns>
    public static Dictionary<int, string> ToDictionary(this Enum enumValue)
    {
        var enumType = enumValue.GetType();
        return Enum.GetValues(enumType)
            .Cast<Enum>()
            .ToDictionary(t => (int)(object)t, t => t.ToString());
    }
3 голосов
/ 05 апреля 2015

+ 1 до Ани .Вот версия VB.NET

Вот версия VB.NET ответа Ани:

Public Enum typFoo
    itemA = 1
    itemB = 2
    itemC = 3
End Enum

Sub example()

    Dim dict As Dictionary(Of Integer, String) = System.Enum.GetValues(GetType(typFoo)) _
                                                 .Cast(Of typFoo)() _
                                                 .ToDictionary(Function(t) Integer.Parse(t), Function(t) t.ToString())
    For Each i As KeyValuePair(Of Integer, String) In dict
        MsgBox(String.Format("Key: {0}, Value: {1}", i.Key, i.Value))
    Next

End Sub

Дополнительный пример

В моем случае я хотел сохранитьпуть к важным каталогам и сохраните их в разделе AppSettings моего web.config файла.Затем я создал enum для представления ключей этих AppSettings ... но моему внешнему инженеру был необходим доступ к этим местам в наших внешних файлах JavaScript.Итак, я создал следующий кодовый блок и разместил его на нашей основной главной странице.Теперь каждый новый элемент Enum автоматически создает соответствующую переменную JavaScript.Вот мой блок кода:

    <script type="text/javascript">
        var rootDirectory = '<%= ResolveUrl("~/")%>';
        // This next part will loop through the public enumeration of App_Directory and create a corresponding JavaScript variable that contains the directory URL from the web.config.
        <% Dim App_Directories As Dictionary(Of String, App_Directory) = System.Enum.GetValues(GetType(App_Directory)) _
                                                                   .Cast(Of App_Directory)() _
                                                                   .ToDictionary(Of String)(Function(dir) dir.ToString)%>
        <% For Each i As KeyValuePair(Of String, App_Directory) In App_Directories%>
            <% Response.Write(String.Format("var {0} = '{1}';", i.Key, ResolveUrl(ConfigurationManager.AppSettings(i.Value))))%>
        <% next i %>
    </script>

ПРИМЕЧАНИЕ. В этом примере я использовал имя перечисления в качестве ключа (не значение int).

3 голосов
/ 07 апреля 2011

Вы можете перечислить по дескрипторам перечисления:

Dictionary<int, string> enumDictionary = new Dictionary<int, string>();

foreach(var name in Enum.GetNames(typeof(typFoo))
{
    enumDictionary.Add((int)((typFoo)Enum.Parse(typeof(typFoo)), name), name);
}

Это должно поместить значение каждого элемента и имя в ваш словарь.

1 голос
/ 07 апреля 2011

Использование отражения:

Dictionary<int,string> mydic = new Dictionary<int,string>();

foreach (FieldInfo fi in typeof(typFoo).GetFields(BindingFlags.Public | BindingFlags.Static))
{
    mydic.Add(fi.GetRawConstantValue(), fi.Name);
}
0 голосов
/ 09 февраля 2019
public class EnumUtility
    {
        public static string GetDisplayText<T>(T enumMember)
            where T : struct, IConvertible
        {
            if (!typeof(T).IsEnum)
                throw new Exception("Requires enum only");

            var a = enumMember
                    .GetType()
                    .GetField(enumMember.ToString())
                    .GetCustomAttribute<DisplayTextAttribute>();
            return a == null ? enumMember.ToString() : a.Text;
        }

        public static Dictionary<int, string> ParseToDictionary<T>()
            where T : struct, IConvertible
        {
            if (!typeof(T).IsEnum)
                throw new Exception("Requires enum only");

            Dictionary<int, string> dict = new Dictionary<int, string>();
            T _enum = default(T);
            foreach(var f in _enum.GetType().GetFields())
            {
               if(f.GetCustomAttribute<DisplayTextAttribute>() is DisplayTextAttribute i)
                    dict.Add((int)f.GetValue(_enum), i == null ? f.ToString() : i.Text);
            }
            return dict;
        }

        public static List<(int Value, string DisplayText)> ParseToTupleList<T>()
            where T : struct, IConvertible
        {
            if (!typeof(T).IsEnum)
                throw new Exception("Requires enum only");

            List<(int, string)> tupleList = new List<(int, string)>();
            T _enum = default(T);
            foreach (var f in _enum.GetType().GetFields())
            {
                if (f.GetCustomAttribute<DisplayTextAttribute>() is DisplayTextAttribute i)
                    tupleList.Add(((int)f.GetValue(_enum), i == null ? f.ToString() : i.Text));
            }
            return tupleList;
        }
    }
...