nate nate - 2 months ago 6
ASP.NET (C#) Question

How to display enum list into a string C# ASP.NET

I have an

enum
and the list has to items per value. I would like to be able to display the
enum list
to end user in a textbox using the string. Here is my enum:

enum CMD
{
COMMANDS, CMD = 0,
ONE, O = 1,
TWO, T = 2,
THREE, TH = 3,
FOUR, F = 4,
FIVE, FI = 5,
SIX, S = 6,
SEVEN, SE = 7
}


Here is what I have tried to accomplish this with the following code, using to
value
of the enum to display both valued list items:

CMD cmd = (CMD)Enum.Parse(typeof(CMD), input);
if (cmd == CMD.COMMANDS)
{
sb.Clear();
sb.AppendLine("List the commands:");
sb.AppendLine(((CMD)0).ToString() + "," + ((CMD)0).ToString("F").Split(',').Last());
sb.AppendLine(((CMD)1).ToString() + "," + ((CMD)1).ToString("F").Split(',').Last());
sb.AppendLine(((CMD)2).ToString() + "," + ((CMD)2).ToString("F").Split(',').Last());
sb.AppendLine(((CMD)3).ToString() + "," + ((CMD)3).ToString("F").Split(',').Last());
sb.AppendLine(((CMD)4).ToString() + "," + ((CMD)4).ToString("F").Split(',').Last());
sb.AppendLine(((CMD)5).ToString() + "," + ((CMD)5).ToString("F").Split(',').Last());
sb.AppendLine(((CMD)6).ToString() + "," + ((CMD)6).ToString("F").Split(',').Last());
sb.AppendLine(((CMD)7).ToString() + "," + ((CMD)7).ToString("F").Split(',').Last());
textbox.Text = sb.ToString();
}


The output I get is:

List the commands:
CMD,COMMANDS
O, O
T, T
TH, TH
F, F
FI, FI
S, S
SEVEN, SE


I want to output to be like this:

COMMANDS, CMD
ONE, O
TWO, T
THREE, TH
FOUR, F
FIVE, FI
SIX, S
SEVEN, SE


How can I accomplish the output like I want?

Answer

How about something like the following:

        var dictonary = new Dictionary<CMD, List<string>>();
        var names = Enum.GetNames(typeof(CMD));
        foreach (var name in names)
        {
            var value = (CMD)Enum.Parse(typeof(CMD), name);
            if(!dictonary.ContainsKey(value))
                dictonary.Add(value, new List<string>() {name});
            else
                dictonary[value].Add(name);
        }

This way you have a dictionary of the enum descriptions with the values and you can implement the result as you wish.