簡體   English   中英

如何使用相同的鍵但累積值從另一個字典填充字典

[英]How to populate a dictionary from another with same keys but values cumulated

我正在尋找使用C#,LINQ解決練習的幫助。

我有一本以DateTime為鍵, decimal為值的字典。 我正在嘗試編寫一種方法,該方法返回另一個字典,該字典的值是該年內前幾個月和當前月份的所有值的總和。 對於下一年,該過程將重復進行。

輸入字典:

01/31/2015  100
02/28/2015  100
03/31/2015  100
;
; and so on
;
01/31/2017  200
02/28/2017  200
03/31/2017  200

輸出應如下所示:

01/31/2015  100
02/28/2015  200
03/31/2015  300
;
;
01/31/2017  200
02/28/2017  400
03/31/2017  600

這是我到目前為止所做的。 它計算總計,但不重置下一年。 在2016年1月,它將Jan的值添加到上一個總和。 我猜在寫Aggregate()之前需要一個GroupBy。

public static IDictionary<DateTime, decimal?> RunningTotal_NotResettingForNextYear(this IDictionary<DateTime, decimal?> inputDictionary)
{

    IDictionary<DateTime, decimal?> runningTotalDictinary =
        new Dictionary<DateTime, decimal?>(inputDictionary.Count);
    inputDictionary.Aggregate((decimal?)0, (sum, value) =>
    {
        sum = sum + value.Value;
        runningTotalDictinary.Add(value.Key, sum);
        return sum;
    });

    return runningTotalDictinary;
}

缺少的部分是GroupBy方法。

  • 首先,按年份分組輸入字典。
  • 然后使用累加器(受F#啟發)逐組計算每個項目的新值
  • 將組合並到一個列表中。
  • 創建新的字典。

然后是最終代碼:

var newDico = inputDictionary.OrderBy(i => i.Key).GroupBy(i => i.Key.Year).SelectMany(
    group =>
        {
            decimal? accumulator = 0;
            return
            group.Select(
                element =>
                    new { Key = element.Key, Value = (accumulator += element.Value)});
        }).ToDictionary(accGroupItem => accGroupItem.Key, accGroupItem => accGroupItem.Value);

或使用臨時累加器字典:

var dicoAcc = inputDictionary
                  .Select(i => i.Key.Year)
                  .Distinct()
                  .ToDictionary(year => year, _ => (decimal?)0);

var newDico = inputDictionary
                  .ToDictionary(i => i.Key, i => dicoAcc[i.Key.Year] += i.Value);
int year = 0;
decimal yearlyTotal = 0;
foreach (var kvp in sourceDict.OrderBy(x => x.Key))
{
  if (kvp.Key.Year != year)
  {
    year = kvp.Year;
    yearlyTotal = 0;
  }
  yearlyTotal += kvp.Value;
  destDict[kvp.Key] = yearlyTotal;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM