Reputation: 1220
I am trying to save an enum
as a comma-separated list in a DB.
I know I can do something like this to actually store a comma separated list:
part.MyProperty = new[] {"foo", "bar"};
and the DB would have an entry "foo, bar".
What I don't know how to do is how to store an enum
, such as:
public enum Choices { Choice1, Choice2, Choice3 }
I gather I have to use Parse
and ToString
to use the enum
values, but I am not sure how to do it.
This doesn't seem right:
part.MyProperty = new[] return from name in Enum.GetNames(typeof(T))
let enumValue = Convert.ToString((T)Enum.Parse(typeof(T), name, true))
Any thoughts?
Upvotes: 5
Views: 10095
Reputation: 28618
[Flags]
public enum Choices {
Choice1 = 1,
Choice2 = 2,
Choice3 = 4
}
Choices a = Choices.Choice1 | Choices.Choice3;
Console.WriteLine(a.ToString());
outputs: Choice1, Choice3
Upvotes: 0
Reputation: 5398
Also you can build your own utitlity method that will get enums name in more nice syntax:
public static TEnum[] GetEnumValues<TEnum>() where TEnum : struct {
return (TEnum[])Enum.GetValues(typeof(TEnum));
}
and then:
Choices[] choices = GetEnumValues<Choices>();
or
part.MyProperty = GetEnumValues<Choices>().Select(n=>n.ToString()).ToArray()
;
Upvotes: 0
Reputation: 460288
What's wrong with part.MyProperty = Enum.GetNames(typeof(Choices));
?
To get a comma separated list, use String.Join
:
string csvEnums = string.Join(",", Enum.GetNames(typeof(Choices)));
Upvotes: 10