如何使用LINQ枚举字典

本文关键字:字典 枚举 LINQ 何使用 | 更新日期: 2023-09-27 18:05:42

我有以下内容

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];

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

如何使用LINQ枚举字典

你可以这样做:

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