EnumToDictionary
/// <summary> /// Converts Enumeration type into a dictionary of names and values /// </summary> /// <param name="t">Enum type</param> public static IDictionary<string, int> EnumToDictionary(this Type t) { if (t == null) throw new NullReferenceException(); if (!t.IsEnum) throw new InvalidCastException("object is not an Enumeration"); string[] names = Enum.GetNames(t); Array values = Enum.GetValues(t); return (from i in Enumerable.Range(0, names.Length) select new { Key = names[i], Value = (int)values.GetValue(i) }) .ToDictionary(k => k.Key, k => k.Value); }Example:
var dictionary = typeof(UriFormat).EnumToDictionary(); /* returns key => value SafeUnescaped => 3 Unescaped => 2 UriEscaped => 1 */
Description
Converts an Enumeration type into a dictionary of its names and values.
Details
- Author: Daniel Gidman
- Submitted on: 3-12-2010 21:50:29
- Language: C#
- Type: System.Type
- Views: 5748
Double click on the code to select all.