Sring[] to List<MyEnumeration>

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I have a Role Enumeration. For example:

public enum Role {
Administrator = 1,
Collaborator,
Visitor
} // Role

How can create a List<Role> from a string array that contains roles as
items. For example:
"Administrator,Collaborator"

If possible using a lambda expression.

Thanks,
Miguel
 
shapper said:
Hello,

I have a Role Enumeration. For example:

public enum Role {
Administrator = 1,
Collaborator,
Visitor
} // Role

How can create a List<Role> from a string array that contains roles as
items. For example:
"Administrator,Collaborator"

If possible using a lambda expression.

MyString.Split(',').Select(s => Enum.Parse(typeof(Role), s, true)).ToList()

Michael
 
string values = "Administrator,Collaborator";
List<Role> roles = values.Split(',').ToList().ConvertAll(r =>
(Role)Enum.Parse(typeof(Role), r));
roles.ForEach(r => Console.WriteLine(r.ToString()));
Console.ReadLine();
 
Peter Morris said:
string values = "Administrator,Collaborator";
List<Role> roles = values.Split(',').ToList().ConvertAll(r =>
(Role)Enum.Parse(typeof(Role), r));
roles.ForEach(r => Console.WriteLine(r.ToString()));
Console.ReadLine();

Here's an interesting tip. You can pass a delegate into ForEach with a
single parameter. Because WriteLine has a single parameter you can just
write:

roles.ForEach(Console.WriteLine);

This works because using the function name without brackets creates a
delegate to that function.

Michael
 
Back
Top