C# 在字典中添加字典的int值
我有一本字典,我正在尝试添加另一本字典中的值 下面是我的字典:C# 在字典中添加字典的int值,c#,linq,lambda,console-application,C#,Linq,Lambda,Console Application,我有一本字典,我正在尝试添加另一本字典中的值 下面是我的字典: Dictionary<string, Dictionary<string, int>> dic = new Dictionary<string, Dictionary<string, int>>(){ { "first", new Dictionary<string, int>() {
Dictionary<string, Dictionary<string, int>> dic = new Dictionary<string, Dictionary<string, int>>(){
{
"first", new Dictionary<string, int>()
{
{ "test1", 21 },
{ "test2", 1 },
{ "test3", 21 },
{ "test4", 122 },
}
},
{
"second", new Dictionary<string, int>()
{
{ "test1", 33 },
{ "test2", 22 },
{ "test3", 2 },
{ "test4", 1 },
}
},
{
"third", new Dictionary<string, int>()
{
{ "test1", 41 },
{ "test2", 31 },
{ "test3", 12 },
{ "test4", 11 },
}
},
};
但这是一个错误
Severity Code Description Project File Line Suppression Status
Error CS0411 The type arguments of the method "Enumerable.SelectMany <TSource, TResult> (IEnumerable <TSource>, Func <TSource, IEnumerable <TResult>>)" cannot be inferred based on usage. Try to explicitly specify the type arguments. CalculadoraLancamento C: \ Users \ sergi \ source \ repos \ CalculadoraLancamento \ CalculadoraLancamento \ Form1.cs 183 Active
严重性代码描述项目文件行抑制状态
错误CS0411无法根据用法推断方法“Enumerable.SelectMany(IEnumerable,Func)”的类型参数。尝试显式指定类型参数。CalculadoRancamento C:\Users\sergi\source\repos\CalculadoRancamento\CalculadoRancamento\Form1.cs 183处于活动状态
您要查找的查询是:
int totalTest1 =
dic
.SelectMany(x => x.Value)
.Where(z => z.Key == "test1")
.Select(z => z.Value)
.Sum();
SelectMany
将外部字典扁平化为一个IEnumerable
,这很容易在键上过滤,然后在值上过滤Sum
对于给定的示例数据,我得到95
您可能不需要对内部字典执行LINQ查询,因为您只是通过键访问字典中的值:
int totalTest1 = dic.Sum(x => x.Value["test1"]);
如果您不确定内部字典是否始终包含指定的键,则可以在访问之前检查:
int totalTest1 = dic.Sum(x => x.Value.TryGetValue("test1", out int result) ? result : 0);
另一个变量是95
Console.WriteLine(dic.SelectMany(x => x.Value)
.Where(x => x.Key == "test1")
.Sum(x => x.Value)); // put criteria into SUM
与使用TryGetValue
相比,这实际上执行得稍微好一点。错误是什么?在selectmany部分中的lambda错误您可以更具体一点吗?包括整个错误消息pleaseCompile error或runtime error?这些内部字典无效,因为它们包含重复的键(您有多个键为“test1”的条目)
Console.WriteLine(dic.SelectMany(x => x.Value)
.Where(x => x.Key == "test1")
.Sum(x => x.Value)); // put criteria into SUM