Follow @endyourif rss Facebook LinkedIn

C# - Convert an Enum to a list C# - Convert an Enum to a list

Published on Mar 27, 2019

Enums are great to help you strongly reference values without using "magic" strings. Normally I use them in conditional if statements. However, recently I wanted to get all values into a List<T>, where T is your Enum. Let's explore how Enum.GetValues will help.

Using Enum.GetValues

Using the Enum.GetValues you can cast your enum type to an IEnumerable followed by a ToList if you wish to convert it into a list.

Below is a full example of converting an enum called AnEnum into a List<AnEnum>:

var listOfEnums = Enum.GetValues(typeof(AnEnum)).Cast().ToList();

Tags: ASP.NET MVC and Web API Tutorial | enum | tolist

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP