What is the best practice to convert an enum
to an list of Id/Name-objects?
Enum
:
public enum Type
{
Type1= 1,
Type2= 2,
Type3= 3,
Type4= 4
}
Object
:
public class TypeViewModel
{
public int Id { get; set; }
public string Name { get; set; }
}
Something like:
var typeList = new List<TypeViewModel>();
foreach (Type type in Enum.GetValues(typeof(Type)))
{
typeList.Add(new TypeViewModel(type.Id, type.Name));
}
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.
To convert an enum to an array of objects: Use the Object. keys() method to get an array of the enum's keys. Filter out the unnecessary values for numeric enums.
VB.NET Enum Methods A Format method is used to convert an enum type value to a specified string format. As the name suggests, the GetName function is used to get the specified item's name from the enumeration list. A GetNames method is used to retrieve all available names from a specified enumeration list as an array.
Enum Class MethodsReturns true one or more bit fields are set in the current instance. Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. Returns the string representation of the value of this instance.
Use LINQ:
var typeList = Enum.GetValues(typeof(Type))
.Cast<Type>()
.Select(t => new TypeViewModel
{
Id = ((int)t),
Name = t.ToString()
});
Result:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With