Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List<Enum> to List<string>

I have a list of enum values:

public static readonly List<NotifyBy> SupportedNotificationMethods = new List<NotifyBy> {
   NotifyBy.Email, NotifyBy.HandHold };

I would like to output it as a comma separated list. (EG: "Email, Handhold")

What is the cleanest way of doing this?

like image 322
Ryan Sampson Avatar asked Nov 16 '11 19:11

Ryan Sampson


People also ask

How to list all enum values c#?

To get all values of an enum, we can use the Enum. GetValues static method. The Enum. GetValues method returns an array of all enum values.

How do you convert a string value to a specific enum type in C#?

TryParse() method converts the string representation of enum member name or numeric value to an equivalent enum object. The Enum. TryParse() method returns a boolean to indicate whether the specified string is converted to enum or not. Returns true if the conversion succeeded; otherwise, returns false .

What can an enum include?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.


1 Answers

Perhaps this:

var str = String.Join(", ", SupportedNotificationMethods.Select(s => s.ToString()));

You can read more about the String.Join method at MSDN. Older versions of String.Join don't have an overload that takes an IEnumerable. In that case just call ToArray() after select.

like image 165
vcsjones Avatar answered Sep 18 '22 17:09

vcsjones