我有两个枚举
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
}
我想创建一个具有这样的值的字典
(键,值)->(持续时间int值,price int值) 例如(30,895),(45,1495)
这是我在下面尝试的方法,但它只获取两个的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)等
答案 0 :(得分:0)
要根据需要构建Dictionary,您需要使用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]}");
}
答案 1 :(得分:0)
您可以将每个枚举转换为列表,然后使用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);
}