我有两个数组字典,它们相乘并存储在字符串和int []的字典中。代码工作
public class Program
{
public static void Main(string[] args)
{
int[] a = {1,0,3,4,0};
int[] b = { 3, 0, 9, 10, 0};
int[] c = {2,3,3,5,0};
var ret = new Dictionary<string, int[]>();
ret.Add("Jack", a);
ret.Add("Jane", b);
ret.Add("James", c);
var multipliers = new Dictionary<string, int>();
multipliers.Add("Jack", 2);
multipliers.Add("Jane", 3);
multipliers.Add("James", 5);
var results = new Dictionary<string, int[]>();
foreach (var item in ret)
{
int[] arr= new int[item.Value.Length];
for (int i = 0; i < item.Value.Length; i ++)
{
int d = item.Value[i] * multipliers[item.Key];
arr[i] = d;
}
results.Add(item.Key,arr);
}
}
}
最有效的方法是什么?有没有办法同时做到这一点?
答案 0 :(得分:1)
以下代码段是并行执行此操作的方法:
var results = new ConcurrentDictionary<string, int[]>();
Parallel.ForEach(ret, pair =>
{
var srcArr = pair.Value;
var arr = new int[srcArr.Length];
var multBy = multipliers[pair.Key];
for (var i = 0; i < srcArr.Length; i++)
{
var d = srcArr[i] * multBy;
arr[i] = d;
}
results[pair.Key] = arr;
});