Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum to List<Object> (Id, Name)

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));
}
like image 431
Palmi Avatar asked May 05 '16 17:05

Palmi


People also ask

How do I create 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 I convert enum to array?

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.

How do you retrieve all available names from a specified enumeration list as an array?

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.

Can we return enum in C#?

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.


1 Answers

Use LINQ:

var typeList = Enum.GetValues(typeof(Type))
               .Cast<Type>()
               .Select(t => new TypeViewModel
               {
                   Id = ((int)t),
                   Name = t.ToString()
               });

Result:

enter image description here

like image 73
Salah Akbari Avatar answered Oct 31 '22 20:10

Salah Akbari