【问题标题】:How to fill a SortedList with a Dictionary as TValue如何用字典作为 TValue 填充 SortedList
【发布时间】:2019-09-10 15:04:51
【问题描述】:

我想使用以下方法,但作为业余程序员,我无法理解如何填充(格式化?)将用作该方法输入的 SortedList。 我有一个带有 DateTime 的 sql 表和一个始终关联“关闭”字符串的值(参见代码)

看了几个答案,都没有结论

public static void AddBollingerBands(ref SortedList<DateTime, Dictionary<string, double>> data, int period, int factor)
{
    double total_average = 0;
    double total_squares = 0;

    for (int i = 0; i < data.Count(); i++)
    {
        total_average += data.Values[i]["close"];
        total_squares += Math.Pow(data.Values[i]["close"], 2);

        if (i >= period - 1)
        {
            double total_bollinger = 0;
            double average = total_average / period;

            double stdev = Math.Sqrt((total_squares - Math.Pow(total_average,2)/period) / period);
            data.Values[i]["bollinger_average"] = average;
            data.Values[i]["bollinger_top"] = average + factor * stdev;
            data.Values[i]["bollinger_bottom"] = average - factor * stdev;
.......
......

【问题讨论】:

  • 您在尝试执行此操作时遇到了什么问题?
  • 字典和 SortedList 似乎都不是布林带数据的正确选择。我会使用按日期排序的类和集合

标签: c# dictionary sortedlist


【解决方案1】:

使用 .Values 只是一个获取操作。结果不是对排序列表中元素的引用,而是一个不可变的 var。

忽略未正确使用 SortedList 的问题,如果您直接通过其键引用元素,则只能更改 sortedList 的值:

data[keyValue]["total_bollinger"] = average;

上面的代码行会相应地更新列表中的值。

我建议不要通过 data.Count() 遍历列表,而是像这样遍历键:

            var keys = data.Keys;
            foreach(var key in data.Keys)
            {
                double total_bollinger = 0;
                double average = total_average / period;

                double stdev = Math.Sqrt((total_squares - Math.Pow(total_average, 2) / period) / period);
                data[key]["total_bollinger"] = total_average;
            }

【讨论】:

  • 我从谷歌搜索后得到的其他方法中选择了这种布林带方法,因为代码行很少。这是链接stackoverflow.com/questions/14635735/…,我认为这没问题,因为我没有看到任何反驳。从你们的 cmets 我了解到我必须寻找一种更好的方法(类?)来计算布林线值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
相关资源
最近更新 更多