C
C#6mo ago
hugi

How do I cast my enum to a list of custom object?

(yes I am aware of dictionary, but I want to use custom object in this case) When I did it to dictionary I was doing the following: var dict = Enum.GetValues(typeof(T)) .Cast<T>().ToDictionary(t => (int)(object)t, t => getEnumString(t.ToString())); But I wasn't able to figure out how to change that to cast to custom object instead, or do I just convert the dict above into custom object after? Is there a way to not do that? custom object myObject: id: number, value: string
5 Replies
TheSnowOwl
TheSnowOwl6mo ago
i think ill need more information on what youre trying to achieve your custom object, is that a class, a struct, or an anonymous type? where id is the value of the enum. or the index in the enum where the value is? the value being the name of the enum value? or the numeral value of the enum value as a string?
hugi
hugi6mo ago
my custom object is a class id: value of enum value: the enum value i.e. enum: Spring = 4, Object id=4, value=Spring
TheSnowOwl
TheSnowOwl6mo ago
ah, i see give me a moment then is something like this what you're looking for?
class MyClass
{
public int ID { get; set; }
public string Value { get; set; }
}

enum Seasons
{
Winter = 1,
Spring,
Summer,
Autumn
}

List<MyClass> GetData<TEnumType>() where TEnumType : Enum
{
var list = new List<MyClass>();
var enumValueNames = Enum.GetNames(typeof(TEnumType));
foreach (string name in enumValueNames)
{
TEnumType enumType = (TEnumType)Enum.Parse(typeof(TEnumType), name);
list.Add(new()
{
ID = (int)Convert.ChangeType(enumType, typeof(int)),
Value = name
});
}
return list;
}

void Demo()
{
var data = GetData<Seasons>();

/*
data will contain 4 items with ID and Value properties

1, id = 1, value = "Winter"
2, id = 2, value = "Spring"
3, id = 3, value = "Summer"
4, id = 4, value = "Autumn"
*/
}
class MyClass
{
public int ID { get; set; }
public string Value { get; set; }
}

enum Seasons
{
Winter = 1,
Spring,
Summer,
Autumn
}

List<MyClass> GetData<TEnumType>() where TEnumType : Enum
{
var list = new List<MyClass>();
var enumValueNames = Enum.GetNames(typeof(TEnumType));
foreach (string name in enumValueNames)
{
TEnumType enumType = (TEnumType)Enum.Parse(typeof(TEnumType), name);
list.Add(new()
{
ID = (int)Convert.ChangeType(enumType, typeof(int)),
Value = name
});
}
return list;
}

void Demo()
{
var data = GetData<Seasons>();

/*
data will contain 4 items with ID and Value properties

1, id = 1, value = "Winter"
2, id = 2, value = "Spring"
3, id = 3, value = "Summer"
4, id = 4, value = "Autumn"
*/
}
hugi
hugi6mo ago
from just reading it yes is what i am looking for! thanks will test it out thanks it was perfect!!
Want results from more Discord servers?
Add your server