【问题标题】:Get values from a class into a dictionary从类中获取值到字典中
【发布时间】:2022-01-02 18:20:02
【问题描述】:

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

我想在另一个项目中使用这些值,并在传递对象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});

还有一些其他的推导,但不能让它工作。

【问题讨论】:

    标签: c# class select


    【解决方案1】:

    使用ToDictionary 的重载和两个Funcs 作为参数。第一个Func 将选择您的密钥,第二个Func 将选择值。

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

    另请参阅documentation

    【讨论】:

    • 谢谢!正是我想要的:)
    猜你喜欢
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 2016-08-31
    相关资源
    最近更新 更多