2

我有以下

private enum Properties
{ one, two, three }

private Dictionary <Properties, String> PropertyToString;
private Dictionary <String, Properies> StringToProperty;

如何使用 LINQ 填充每个字典,以便可以使用以下内容?是否有一行 LINQ 语句可以填充每个语句?

Properties MyResult = StringToProperty["One"];
String MySResult = PropertyToString[Properties.One];

我特别想在第二种情况下使用 actaull 属性来索引。

4

1 回答 1

3

你可以这样做:

private Dictionary<Properties,String> PropertyToString = Enum
    .GetValues(typeof(Properties))
    .Cast<Properties>().
    .ToDictionary(v => v, v => Enum.GetName(typeof(Properties), v));

private Dictionary<String,Properties> StringToProperty = Enum
    .GetValues(typeof(Properties))
    .Cast<Properties>().
    .ToDictionary(v => Enum.GetName(typeof(Properties), v), v => v);

请注意,PropertyToString字典是不必要的,因为您可以这样做:

String MySResult = Enum.GetName(typeof(Proeprties), Properties.One);
于 2013-03-25T00:25:03.480 回答