2013-07-05 36 views
1

我试图在数据库中将enum另存为逗号分隔列表。将枚举存储为以逗号分隔的列表

我知道我可以做这样的事情实际存储的逗号分隔列表:

part.MyProperty = new[] {"foo", "bar"}; 

和DB将有一个入口“富,酒吧”。

我不知道该怎么办是如何存储的enum,如:

public enum Choices { Choice1, Choice2, Choice3 } 

我猜我不得不使用ParseToString使用enum值,但我不知道怎么做。

这似乎并不正确:

part.MyProperty = new[] return from name in Enum.GetNames(typeof(T)) 
    let enumValue = Convert.ToString((T)Enum.Parse(typeof(T), name, true)) 

有什么想法?

+0

请注意在一列中存储多个值违反[第一正常形式](https://en.wikipedia.org/wiki/First_normal_form)。 –

回答

4

part.MyProperty = Enum.GetNames(typeof(Choices));怎么了?

为了得到一个逗号分隔的列表,使用String.Join

string csvEnums = string.Join(",", Enum.GetNames(typeof(Choices))); 
+0

哪里是被调用的字符串 - 对不起,有点n00b – REMESQ

+0

@REMESQ:对不起,我不明白你的问题。我必须承认,我甚至不知道你为什么使用Linq来获得这个值,或者你想如何将它存储在数据库中。 –

+0

@REMESQ,Enum.GetNames()返回一个字符串集合 – AntLaC

0
String.Join(",", Enum.GetNames(typeof(Choices))); 
0

你也可以建立自己的utitlity方法,它将以更漂亮的语法让枚举名称:

public static TEnum[] GetEnumValues<TEnum>() where TEnum : struct { 
    return (TEnum[])Enum.GetValues(typeof(TEnum)); 
} 

和那么:

Choices[] choices = GetEnumValues<Choices>(); 

part.MyProperty = GetEnumValues<Choices>().Select(n=>n.ToString()).ToArray();

0
[Flags] 
public enum Choices { 
    Choice1 = 1, 
    Choice2 = 2, 
    Choice3 = 4 
} 

Choices a = Choices.Choice1 | Choices.Choice3; 

Console.WriteLine(a.ToString()); 

输出:Choice1, Choice3

相关问题