Click here to Skip to main content
15,849,163 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I need to create generic method that return dictionary of Enum values with display attribute name.

I would also like to see if it can be done as an extension method for Enum.

What I have tried:

I only able to do with non generic method.

internal IDictionary<int,string> GetPriorityTypes()
      {
          Dictionary<int, string> priorities = new Dictionary<int, string>();

          foreach (PriorityType item in Enum.GetValues(typeof(PriorityType)))
          {
              priorities.Add((int)item, item.GetDisplayName());
          }

          return priorities;
      }
Posted
Updated 6-Apr-20 11:35am
Comments
Maciej Los 6-Apr-20 15:45pm    
What is PriorityType class declaration and decoration?
istudent 6-Apr-20 17:24pm    
Its an Enum
MadMyche 7-Apr-20 7:57am    
How about you give us a sample of the markup for the Enum, and what you want for the results of this function you want?
You can add these items to this question via the Improve Question widget above

1 solution

How about an Extension Method that can return an int/string dictionary across whatever type of Enum it sees?
C#
namespace System {
	public static class SysExtension {
		public static Dictionary<int, string> ToDictionary(this Enum EnumList) {
			Dictionary<int, string> ED = new Dictionary<int, string>();
			Type ET = EnumList.GetType();
			foreach (int i in Enum.GetValues(ET)) {
				ED.Add(i, Enum.GetName(ET, i));
			}
			return ED;
		}
	}
}
And then you could just call it like so...
C#
Dictionary<int, string> x = new MyEnum().ToDictionary();

Here is the full script I used for testing:
C#
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp1 {
	class Program {
		static void Main(string[] args) {

			Dictionary<int, string> x = new MyEnum().ToDictionary();
			foreach (KeyValuePair<int, string> kvp in x) {
				Console.WriteLine(string.Format("{0}:	{1}", kvp.Key, kvp.Value));
			}
			Console.ReadLine();
		}

		public enum MyEnum {
			Alpha = 1,
			Bravo = 2,
			Charlie = 3,
			Delta = 4,
			Echo = 5,
			Foxtrot = 6,
			Golf = 7,
			Hotel = 8,
			Juliet = 10,
		}
	}
}

namespace System {
	public static class SysExtension {

		public static Dictionary<int, string> ToDictionary(this Enum EnumList) {
			Dictionary<int, string> ED = new Dictionary<int, string>();
			Type ET = EnumList.GetType();
			foreach (int i in Enum.GetValues(ET)) {
				ED.Add(i, Enum.GetName(ET, i));
			}
			return ED;
		}
	}
}
 
Share this answer
 
Comments
istudent 6-Apr-20 17:25pm    
I want to get name from Display Attribute sir.
#realJSOP 7-Apr-20 5:44am    
There is no such property in an Enum object.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900