如何从C#中的另一个字典为字典分配键和值?

时间:2017-03-08 06:22:58

标签: 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;

}

1 个答案:

答案 0 :(得分:1)

您应该只需使用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])});
  }
}