Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a list of member names from Enum?

Tags:

c#

enums

This should be fairly simple question. I'm using DocX library to create new word documents. I wanted to make a test word document to see how each TableDesign (enum) looks like to choose the one I need.

Designs\Styles that can be applied to a table. Namespace: Novacode Assembly: DocX (in DocX.dll) Version: 1.0.0.10 (1.0.0.10)

Syntax:

public enum TableDesign

Member name
Custom
TableNormal
TableGrid
LightShading
LightShadingAccent1
....

And so on. I would like to get a list of those TableDesign's so i could reuse it in a method creating new table with new design for all possibilities, but I don't really know how to get the list from that enum:

foreach (var test in TableDesign) {
      createTable(documentWord, test);
}

How do I get that?

like image 900
MadBoy Avatar asked Aug 09 '10 17:08

MadBoy


People also ask

How do I get all the values in an enum list?

The idea is to use the Enum. GetValues() method to get an array of the enum constants' values. To get an IEnumerable<T> of all the values in the enum, call Cast<T>() on the array. To get a list, call ToList() after casting.

Can you have a list of enums?

You can easily retrieve all the enum 'values' as strings using the static Enum. GetNames method. This gives you a list of all the enum values. If all you want to do is directly display the enum values as is then you're done: You can directly bind those enum values to the drop down's DataSource.

How do I find the name of an enum?

Enum. GetName(Type, Object) Method is used to get the name of the constant in the specified enumeration that has the specified value. Syntax: public static string GetName (Type enumType, object value);

How do I get the enum key in Python?

Use the name attribute on the enum member to get the name, e.g. Sizes.SMALL.name . If you only have the corresponding value, pass the value to the enumeration class and access the name attribute. Copied! You can use the name and value properties on an enum member to get the enum's name and value.


1 Answers

Found answer myself:

    // get a list of member names from Volume enum,
    // figure out the numeric value, and display
    foreach (string volume in Enum.GetNames(typeof(Volume)))
    {
        Console.WriteLine("Volume Member: {0}\n Value: {1}",
            volume, (byte)Enum.Parse(typeof(Volume), volume));
    }

For my specific case I've used:

 foreach (var test in Enum.GetNames(typeof(TableDesign))) {
     testMethod(documentWord, test);
 }

and in testMethod I've:

tableTest.Design = (TableDesign) Enum.Parse(typeof(TableDesign), test); 

It worked without a problem (even if it was slow, but I just wanted to get things quickly (and being onetimer performance didn't matter).

Maybe it will help someone in future too :-)

like image 72
MadBoy Avatar answered Sep 25 '22 03:09

MadBoy