2012-12-12 82 views
0

门槛我有较低的更换值比使用LINQ

int[] source = new[]{ 1, 3, 8, 9, 4 }; 

我应该以替换所有值源,低于某一阈值,以零写什么LINQ查询?

回答

5
int threshold = 2; 
int[] dest = source.Select(i => i < threshold ? 0 : i).ToArray(); 

如果你不希望创建一个新的数组,但使用旧:

for(int index=0; index < source.Length; index++) 
{ 
    if(source[index] < threshold) 
     source[index] = 0; 
} 
2

如果您在(而不是)的阵列更换后真的是,不要使用LINQ,只需

for(int i = 0; i < source.Length; i++) 
    if (source[i] < threshold) 
     source[i] = 0;