How do I convert an enum to a list in C#?
This will return an IEnumerable<SomeEnum>
of all the values of an Enum.
Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>();
If you want that to be a List<SomeEnum>
, just add .ToList()
after .Cast<SomeEnum>()
.
To use the Cast function on an Array you need to have the System.Linq
in your using section.
How to convert enum to list
Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Where(x => x != MyEnum.D).ToList();
Convert Enum to List
Language[] result = (Language[])Enum.GetValues(typeof(Language))
will get you your values, if you want a list of the enums.
If you want a list of the names, use this:
string[] names = Enum.GetNames(typeof(Languages));
C# - Convert list of enum values to list of strings
Since you are using a List
, the easiest solution would be to use the ConvertAll
method to obtain a new List
containing string
representations. Here's an example:
List<string> stringList = myList.ConvertAll(f => f.ToString());
There are other ways to accomplish this, but this way will get the job done and uses syntax that should be in whatever version of .NET you're using because it's been around for a long time.
Convert Enums to List of given type
There may be a better way, but this seems to work:
var list = Enum.GetValues(typeof(ExampleEnum)).Cast<ExampleEnum>().Select(
x => new ListItem { Text = x.ToString(), Value = (int)x }).ToList();
So this will grab all the values from the enum using Enum.GetValues
. Since it returns type Array
, I use Cast<ExampleEnum>
to get them in to a IEnumerable<ExampleEnum>
. Then I Select
each enum value to a ListItem
type. Text
property is created by using ToString
, Value
property is created by casting it to int
.
Convert an enum to List string
Use Enum
's static method, GetNames
. It returns a string[]
, like so:
Enum.GetNames(typeof(DataSourceTypes))
If you want to create a method that does only this for only one type of enum
, and also converts that array to a List
, you can write something like this:
public List<string> GetDataSourceTypes()
{
return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}
You will need Using System.Linq;
at the top of your class to use .ToList()
Convert an Enum to a List object
public static class EnumSerializer
{
public static EnumList EnumToJson<T>() where T : struct, Enum
{
var type = typeof(T);
var values = Enum.GetValues<T>()
.Select(x => new EnumNameValue
{
Id = (int)(object)x,
Description = type.GetField(x.ToString())
.GetCustomAttribute<DescriptionAttribute>().Description
});
return new EnumList { EnumNamesValues = values.ToList() };
}
}
Working example
Enum.GetValues
iterates over the constants declared in your enum.
Of course you can swap out the Description
part with your extension method.
How do I convert an enum to a list and replace '_' with ' ' (space)
You should be able to just do
Enum.GetNames(typeof(EnumType)).Select(item => item.Replace('_',' '));
Enum to List Object (Id, Name)
Use LINQ:
var typeList = Enum.GetValues(typeof(Type))
.Cast<Type>()
.Select(t => new TypeViewModel
{
Id = ((int)t),
Name = t.ToString()
});
Result:
Enum to list as an extension?
What is the correct way to use it as an extension (using the above 2 methods)?
There is no correct way to use it as an extension. Extension methods (similar to instance methods) are used when you have a value (instance) and for instance want to get some information related to that value. So the extension method would make sense if you want to get the description of a single enum
value.
However, in your case the information you need (the list of enum
value/description pairs) is not tied to a specific enum
value, but to the enum
type. Which means you just need a plain static generic method similar to Enum.TryParse<TEnum>
. Ideally you would constrain the generic argument to allow only enum
, but this type of constraint is not supported (yet), so we'll use (similar to the above system method) just where TEnum : struct
and will add runtime check.
So here is a sample implementation:
public static class EnumInfo
{
public static List<KeyValuePair<TEnum, string>> GetList<TEnum>()
where TEnum : struct
{
if (!typeof(TEnum).IsEnum) throw new InvalidOperationException();
return ((TEnum[])Enum.GetValues(typeof(TEnum)))
.ToDictionary(k => k, v => ((Enum)(object)v).GetAttributeOfType<DescriptionAttribute>().Description)
.ToList();
}
}
and usage:
public enum MyEnum
{
[Description("Foo")]
A,
[Description("Bar")]
B,
[Description("Baz")]
C,
}
var list = EnumInfo.GetList<MyEnum>();
Related Topics
Redirect from Action Filter Attribute
How to Refresh C# Datagridview After Update
Dynamically Adding Properties to an Expandoobject
Xml Serialize Generic List of Serializable Objects
The Name 'Configurationmanager' Does Not Exist in the Current Context
String = String + Int: What's Behind the Scenes
How to Pass an Object from Form1 to Form2 and Back to Form1
Memory Address of an Object in C#
How to Make Multi-Language App in Winforms
Must Declare Scalar Variable @Id
Does .Net Provide an Easy Way Convert Bytes to Kb, Mb, Gb, etc.
A Property or Indexer May Not Be Passed as an Out or Ref Parameter
Simple State MAChine Example in C#
C# Short/Long/Int Literal Format
Determine If a Sequence Contains All Elements of Another Sequence Using Linq