Sring[] to List<MyEnumeration>

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
 
M

Michael C

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
 
P

Peter Morris

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();
 
M

Michael C

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Loop an Enumeration 4
Intersection of Lists 5
List. Add, Remove. 1
List. Check items 3
NHibernate QueryOver with Many-to-Many 0
Generics 7
List to EntityCollection 0
Dictionary 3

Top