c# - 在需要时合并多个字典和聚合值
问题描述
我通过在 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 中实现这一点?
解决方案
在我看来,这就是你所需要的:
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());
推荐阅读
- c# - 如何更改richtextbox中2个字符之间的颜色?
- html - 在 IPYNB 中渲染 HTML 块?
- r - 在R中覆盖两个具有不同Y轴的多面线图
- javascript - 无法在 React 中正确使用 SASS/SCSS 样式
- flutter - Dart DateTime.parse timeZoneOffset 始终为 0
- csv - 使用 awk 合并 *.csv 文件并在终端中将文件名添加为列
- python - 如何在 Arduino IDE 中向 http 请求添加标头
- javascript - 为什么我的表格过滤器正在删除表格标题?
- hash - 映射键值对时,哈希如何防止冲突?
- php - 当预期相同的行为时,为什么通过 `auth guard A` 重定向的登录与来自 `auth guard B` 的登录不同?