我有使用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
将-Infinity更改为0的最有效方法是什么?在循环中放置continue
或if statement
函数会起作用吗?我知道我可以使用替换函数并循环遍历字典,这不是很有效。
答案 0 :(得分:3)
由于你可以控制放入字典的值,我会改变
(v, index) => 3 * Math.Log10((double)v / 10)
到
(v, index) => v == 0 ? 0 : 3 * Math.Log10((double)v / 10)
否则,您可以使用ternary operator:
Console.WriteLine("Key = {0}, Value = {1}", item.Key,
item.Value[i] == Double.NegativeInfinity ? 0 : item.Value[i]);
答案 1 :(得分:0)
人们常常使用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());