繁体   English   中英

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

[英]How to assign key and values to a dictionary from another dictionary in C#?

我正在尝试为基于另一个字典的字典分配键和值,如下所示,不清楚如何在 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])});
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM