Monday, January 30, 2012

Best Extension Methods: Convert Enum To Dictionary

Using below extension method you can convert a enum to a dictionary type.
    /// Converts Enumeration type into a dictionary of names and values
    /// Enum type
    public static IDictionary 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);

Compiled By: Rajesh Rolen

Share This!

No comments:

Powered By Blogger · Designed By Seo Blogger Templates