c#有效地替换字典中的无穷大值

本文关键字:无穷大 字典 有效地 替换 | 更新日期: 2023-09-27 18:02:39

我有代码使用LINQ转换字符串,整型到字符串,双精度的字典。下面的代码可以正常工作:

public static void Main(string[] args)
{
    Dictionary<string, int[]> ret = new Dictionary<string, int[]>();
    int[] a = {1,2,0,4,5};
    int[] b = { 0, 6, 9, 0, 12 };
    int[] c = {2,0,3,5,0};
    ret.Add("Al", a);
    ret.Add("Adam", b);
    ret.Add("Axel", c);
    Dictionary<string, double[]> scores = ret.ToDictionary(r=> r.Key,
                         r => r.Value.Select((v, index)=> 
                         3 * Math.Log10((double)v / 10)
                         ).ToArray());

    foreach (var item in scores)
    {
        for (int i = 0; i < item.Value.Length; i ++)
        {
            Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value[i]);
        }
    }

这段代码输出:

Key = Al, Value = -3
Key = Al, Value = -2.09691001300806
Key = Al, Value = -Infinity
Key = Al, Value = -1.19382002601611
Key = Al, Value = -0.903089986991944
Key = Adam, Value = -Infinity
Key = Adam, Value = -0.665546248849069
Key = Adam, Value = -0.137272471682025
Key = Adam, Value = -Infinity
Key = Adam, Value = 0.237543738142874
Key = Axel, Value = -2.09691001300806
Key = Axel, Value = -Infinity
Key = Axel, Value = -1.56863623584101
Key = Axel, Value = -0.903089986991944
Key = Axel, Value = -Infinity

将-∞变为0的最有效方法是什么?在循环中加入continueif statement函数会起作用吗?我知道我可以只使用replace函数并遍历字典,这不是很有效。

c#有效地替换字典中的无穷大值

由于您可以控制放入字典的值,因此我将更改

(v, index) => 3 * Math.Log10((double)v / 10)

(v, index) => v == 0 ? 0 : 3 * Math.Log10((double)v / 10)
否则,您可以直接使用三元操作符:
Console.WriteLine("Key = {0}, Value = {1}", item.Key,
    item.Value[i] == Double.NegativeInfinity ? 0 : item.Value[i]);

人们经常使用linq作为一个单独的行符。忘记什么

var scores = ret.ToDictionary(r => r.Key, r => r.Value.Select((v, index)=>
{
    var result = 3 * Math.Log10((double)v / 10);
    if(double.IsNegative(result))
        result = 0;
    return result;
}).ToArray());