循环遍历字典+乘以所有值

时间:2015-05-08 09:35:42

标签: c# loops dictionary

我有一个Dictionary(dict),它包含string(key)和double(value)。我想做这种数学:

X = (A * B * ... * n) / ((A * B * ... * n) + ((1 - A) * (1 - B) * ... * (1-n)))

其中A,B,...,n是我的词典中的值。

foreach (var number in dict)
{
    A = number.Value;

    X = (A) / (A * (1 - A));
}

2 个答案:

答案 0 :(得分:1)

如果你想迭代这样的值,我不知道为什么你会把它们放在字典中,但是你走了:

Func<double, double, double> multiply = (v1, v2) => v1 * v2;

var product = dict.Values.Aggregate(1, multiply);
var diffProduct = dict.Values.Select(v => 1 - v).Aggregate(1, multiply);
var result = 1 / (1 + diffProduct / product); 

我在这里简化了整体表达,因此它的精确度会降低。

答案 1 :(得分:0)

你走了:

                Dictionary<int, int> dict = new Dictionary<int, int>();
                dict.Add(1, 10);
                dict.Add(2, 20);
                dict.Add(3, 30);
                dict.Add(4, 40);

                double coe1 = 1;
                double series = 1;
                foreach (var number in dict)
                {
                    coe1 *= number.Value;
                    series *= (1 - number.Value);
                }

                double x = coe1 / (coe1 + series);

如果您需要中间结果:

                foreach (var number in dict)
                {
                    coe1 *= number.Value;
                    series *= (1 - number.Value);
                    Console.WriteLine(coe1 / (coe1 + series));
                }