代码之家  ›  专栏  ›  技术社区  ›  chuckd

试图获取字典的枚举值

  •  0
  • chuckd  · 技术社区  · 7 年前

    我有两个枚举

    public enum Duration
    {
        [Display(Name = "30 min")]
        ThirtyMinutes = 30,
        [Display(Name = "45 min")]
        FortyFiveMinutes = 45,
        [Display(Name = "60 min")]
        SixtyMinutes = 60,
        [Display(Name = "75 min")]
        SeventyFiveMinutes = 75,
        [Display(Name = "90 min")]
        NinetyMinutes = 90
    }
    
    public enum Price
    {
        [Display(Name = "$8.95")]
        ThirtyMinutes = 895,
        [Display(Name = "$14.95")]
        FortyFiveMinutes = 1495,
        [Display(Name = "$19.95")]
        SixtyMinutes = 1495,
        [Display(Name = "$24.95")]
        SeventyFiveMinutes = 2495,
        [Display(Name = "$27.95")]
        NinetyMinutes = 2795
    }
    

    我想创建一个字典,它的值如下

    (键,值)—>(持续时间整数值,价格整数值) 例(30895),(451495)

    这是我在下面尝试的,但它只获取两者的duration int值

    public static Dictionary<int, int> GetPriceDictionary()
        {
            Dictionary<int, int> dictionary = new Dictionary<int, int>();
            foreach(var value in Enum.GetValues(typeof(Duration)))
            {
                var number = (int)value;
                var price = Enum.Parse(typeof(Price), number.ToString());
                dictionary.Add(number, (int)price);
            }
            return dictionary;
        }
    

    但这又回来了

    (30,30),(45,45)等

    2 回复  |  直到 7 年前
        1
  •  0
  •   JayV    7 年前

    为了像您想要的那样构造字典,您需要使用 Duration 不是号码

    var price = Enum.Parse(typeof(Price), value.ToString());
    

    更改后,字典现在看起来像:

    30:895
    45:1495
    60:1495
    75:2495
    90:2795
    

    我使用的测试代码,作为参考:

    var dictionary = GetPriceDictionary();
    var keys = dictionary.Keys;
    foreach (var key in keys)
    {
        Debug.WriteLine($"{key}:{dictionary[key]}");
    }
    
        2
  •  0
  •   L_J    7 年前

    您可以将每个枚举转换为列表,然后使用 Zip 创建字典。

    public static Dictionary<int, int> GetPriceDictionary()
    {
        var duration = ((int[])Enum.GetValues(typeof(Duration))).ToList();
        var price = ((int[])Enum.GetValues(typeof(Price))).ToList();
    
        return  duration.Zip(price, (k, v) => new { k, v }).ToDictionary(x => x.k, x => x.v);
    }