首页 > 解决方案 > 在需要时合并多个字典和聚合值

问题描述

我通过在 LINQ 中的 GroupBy 投影上调用 ToDictionary 创建了三个字典。

var dictionaryOne = _repositoryOne.GetData()
.GroupBy(d => new { d.Property1, d.Property2, d.LocalCcyId})
.ToDictionary(d =>
    new
    {
        d.Key.Property1,
        d.Key.Property2,
        d.Key.LocalCcyId
    },
    v => v.Sum(l => ConvertToUsd(effectiveDate, l.LocalCcyId, l.Amount))); 

var dictionaryTwo = _repositoryTwo.GetData()
.GroupBy(d => new { d.Property1, d.Property2, d.LocalCcyId})
.ToDictionary(d =>
    new
    {
        d.Key.Property1,
        d.Key.Property2,
        d.Key.LocalCcyId
    },
    v => v.Sum(l => ConvertToUsd(effectiveDate, l.LocalCcyId, l.Balance))); 

var dictionaryThree = _repositoryThree.GetData()
.GroupBy(d => new { d.Property1, d.Property2, d.LocalCcyId})
.ToDictionary(d =>
    new
    {
        d.Key.Property1,
        d.Key.Property2,
        d.Key.LocalCcyId
    },
    v => v.Sum(l => ConvertToUsd(effectiveDate, l.LocalCcyId, l.Total))); 

我想将这些合并到字典中,并且 i) 总结 USD 和 ii) 中的值按 LocalCcyId 列从键中删除

这将是三个字典中每个字典中出现相同键的实例,我需要汇总所有此类情况的总和。如何在 LINQ 中实现这一点?

标签: c#linq

解决方案


在我看来,这就是你所需要的:

var finalDictionary =
    dictionaryOne
        .Concat(dictionaryTwo)
        .Concat(dictionaryThree)
        .GroupBy(x => new { x.Key.Property1, x.Key.Property2 }, x => x.Value)
        .ToDictionary(x => new { x.Key.Property1, x.Key.Property2 }, x => x.Sum());

或者,使用 LINQ 语法(尽可能):

var finalDictionary =
(
    from x in dictionaryOne.Concat(dictionaryTwo).Concat(dictionaryThree)
    group x.Value by new { x.Key.Property1, x.Key.Property2 }
)
    .ToDictionary(x => new { x.Key.Property1, x.Key.Property2 }, x => x.Sum());

推荐阅读