Mdb Mdb - 1 month ago 6
C# Question

Create a List of objects using enum data C#

So I have an enum:

public enum myEnum
{
IBM = 1,
HP = 2,
Lenovo = 3
}


I have a
Brand
class

public class Brand
{
public Brand(string name, int id)
{
Name = name;
Id = id;
}

public string Name { get; private set; }
public int Id { get; private set; }
}


I want to create a List of
Brand
objects populated with the data from the
MyEnum
. Something like:

private IEnumerable<Brand> brands = new List<Brand>
{
new Brand(myEnum.IBM.ToString(), (int) myEnum.IBM),
new Brand(myEnum.HP.ToString(), (int) myEnum.HP),
new Brand(myEnum.Lenovo.ToString(), (int) myEnum.Lenovo),
};


I can create two arrays - one with enum names and the other with enum ids and foreach them to create Brand object for every iteration but wonder if there is a better solution.

Finally, I am going with Royi Mindel solution as according to me it is the most appropriate . Many thanks to Daniel Hilgarth for his answer and his help making Royi Mindel suggestion work. I would give credit to both of them for this question if I could.

public static class EnumHelper
{
public static IEnumerable<ValueName> GetItems<TEnum>()
where TEnum : struct, IConvertible, IComparable, IFormattable
{
if (!typeof(TEnum).IsEnum)
throw new ArgumentException("TEnum must be an Enumeration type");

var res = from e in Enum.GetValues(typeof(TEnum)).Cast<TEnum>()
select new ValueName() { Id = Convert.ToInt32(e), Name = e.ToString() };

return res;
}
}

public struct ValueName
{
public int Id { get; set; }
public string Name { get; set; }
}

Answer

I would suggest making a general ValueName class to fit all enums and not make specific classes to fit specific enums

public static class EnumHelper
{
    public static IEnumerable<ValueName> GetItems<TEnum>() 
        where TEnum : struct, IConvertible, IComparable, IFormattable
    {
        if (!typeof(TEnum).IsEnum)
            throw new ArgumentException("TEnum must be an Enumeration type");

        var res = from e in Enum.GetValues(typeof(TEnum)).Cast<TEnum>()
                    select new ValueName() { Value = Convert.ToInt32(e), Name = e.ToString()};

        return res;
    }

}

public struct ValueName
{
    public int Value { get; set; }
    public string Name { get; set; }
}

then you just do :

EnumHelper.GetItems<myEnum>()