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