c# - 如何在 C# 中将键和值分配给另一个字典中的字典?

标签 c# dictionary

我正在尝试为基于另一个字典的字典分配键和值,如下所示,我不清楚如何在 C# 中执行此操作,我在下面为其编写了伪代码?任何人都可以帮助如何在C#?

类:

public class BuildMetrics
{
    public Dictionary<string, string[]> BitSanity { get; set; }
}

代码:-

var metrics = new BuildMetrics();
Dictionary<int, int[]> bitSanityResults = new Dictionary<int,int[]>(); 

try
{
    bitSanityResults = bitDB.bit_sanity_results.Where(x => x.software_product_build_id == latestBuildProductBuildId)
                            .ToDictionary(x => x.test_suite_id, x => 
                             new int[] { x.pass_count, x.fail_count });
}
catch(System.ArgumentException e)
{
    Console.WriteLine(e);
}
//pseudocode
foreach (var item in bitSanityResults){
    metrics.BitSanity[key] = bitDB.test_suites.Where(x => x.id == item.Key)
                                              .Select(x => x.suite_name).FirstOrDefault();
    metrics.BitSanity[Value1] = item.Value1/item.Value2;
    metrics.BitSanity[Value2] = item.Value1 + item.Value2;

}

最佳答案

您应该能够简单地使用 Add() 方法。

foreach (var item in bitSanityResults)
{
  //It looks like you select a string here. Notice that your Dictionary needs int as key!!!
  int key = bitDB.test_suites.Where(x => x.id == item.Key).Select(x => x.suite_name).FirstOrDefault();

  metrics.Add(key, new[] {item.Value[0]/item.Value[1], item.Value[0]+item.Value[1] });
}

希望对您有所帮助。如果我误解了你的问题,请告诉我。

更新:

我添加了一些空检查来向您展示如何解决您的 NullReference 问题:

foreach (var item in bitSanityResults)
{
  //It looks like you select a string here. Notice that your Dictionary needs int as key!!!
  int key = bitDB.test_suites.Where(x => x.id == item.Key).Select(x => x.suite_name).FirstOrDefault();

  if (metrics != null &&
      item != null &&
      item.Value[0] != null &&
      item.Value[1] != null)
  {
     metrics.BitSanity.Add(key, new[] {Convert.ToString(item.Value[0]), Convert.ToString(item.Value[1])});
  }
}

关于c# - 如何在 C# 中将键和值分配给另一个字典中的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42664346/

相关文章:

c# - 没有找到隐式类型数组的最佳类型

Python 字典 : adding a value in a key already made without losing the original value

python-3.x - Python Pandas - 根据索引、列使用字典更新行

STL - 在 C++ 中,当键是带字符串的结构时,如何在带有仿函数的映射上使用 find_if?

javascript - WebApi 到 Angular 属性键全部都是小写?

c# - 在 Android Xamarin 中设置对话框按钮点击监听器

c# - 如何将 UserControl.ascx 的代码隐藏类放入另一个库中

python - 具有单独 TTL 的过期字典

javascript - 在javascript中映射嵌套数组

c# - 如何将 linq 查询绑定(bind)到转发器?