从 class 中获取值到字典中

Get values from a class into a dictionary

我有一个包含 ID (int)、日期 (DateTime) 和价格 (double) 列表的对象 volresult

我想在另一个项目中使用这些值并在传递对象时避免循环引用 volresult 我想将日期和价格作为 Dictionary<DateTime, Double>.

传递

我试过:

var try1 = results.values.Select(x => new {x.Date, x.Prices}).ToDictionary(DateTime, Double);
var try2 = results.values.ToDictionary<DateTime, Double>(x => new {x.Date, x.Prices});
var try3 = results.values.SelectMany(x => x.Date, y => y.Prices});

还有一些其他的推导,但无法使其发挥作用。

使用带有两个 Func 作为参数的 ToDictionary 的重载。第一个 Func 将 select 您的密钥,第二个 Func 将 select 值。

var dictionary = result.values.ToDictionary(x => x.Date, x => x.Prices);

另见 documentation