How do I convert an enum type to list?

4

Is there any way to convert a Enum to List ?

public enum TiposHospedagem
{
    Casa = 1,
    Hotel = 2,
    Pousada = 3,
    CasaCampo = 4
}

I'm trying to get enum and add to the list, but foreach does not want to do this.

protected void Page_Load(object sender, EventArgs e)
{
    var lista = new List<Int32>();

    foreach (var th in TiposHospedagem)
    {
        lista.Add(Convert.ToInt32(th));
    }
}
    
asked by anonymous 31.08.2016 / 17:13

2 answers

8

As answer in the SO , you can do this:

using System;
using System.Linq;
using static System.Console;
using System.Collections.Generic;

public class Program {
    public static void Main() {
        var lista = new List<int>();
        foreach (int item in Enum.GetValues(typeof(TiposHospedagem))) {
            lista.Add(item);
        }
        foreach (var item in lista) {
            WriteLine(item);
        }
    }
}

public enum TiposHospedagem {
    Casa = 1,
    Hotel = 2,
    Pousada = 3,
    CasaCampo = 4
}

See working on dotNetFiddle .

The solution will obviously vary as needed. Then another possibility would be:

var lista = Enum.GetValues(typeof(TiposHospedagem)).Cast<int>().ToList();

See running on dotNetFiddle .

It may not be very performative as it uses reflection, but should meet most needs well.

This code takes all the existing values in the enumeration, makes a cast on each member for an integer, since it is the type you want (if you wanted, another could be a problem) and converts to the list. All this using LINQ, so you can do it in one line.

    
31.08.2016 / 17:23
2

You can use the following syntax:

Enum.GetValues(typeof(MeuEnumerador)).Cast<MeuEnumerador>();

And this will return a specialized IEnumerable interface to type MyEnumerator.

To convert the data through this interface to a list you must use the ".ToList ()" method of it

Note: You need to include the System.Linq namespace in your code to use this code.

Credits: Answer based on the SO-En question located in this link

    
31.08.2016 / 17:19