所以假设我有一个字符串数组:
string[] values = new[] { "1", "2", "3", "1.5", "56.5", "8" };
假设我必须遍历这些值并执行以下操作:
string[] values = new[] { "1", "2", "3", "1.5", "56.5", "8" };
for (int i = 0; i < values.Length; i++)
{
file[i].Value = ((Int32)Math.Abs(Math.Round(Double.Parse(values[i]), MidpointRounding.ToEven))).ToString();
}
这与这样做基本相同:
string[] values = new[] { "1", "2", "3", "1.5", "56.5", "8" };
for (int i = 0; i < values.Length; i++)
{
String strValue = values[j];
Double dblValue = Double.Parse(strValue);
Double dblRoundedValue = Double.Parse(dblValue);
Int32 intValue = (Int32)dblRoundedValue;
Int32 intAbsValue = Math.Abs(intValue);
String finalValue = intAbsValue.ToString();
file[i].Value = finalValue;
}
该数组中可能有超过一百万个值,那么有没有办法让这个过程更有效率?
最佳答案
这个操作本质上是可并行的(如果这是一个词)。一个 Parallel.ForEach
循环、并行 Linq 管道或类似的东西,会缩短执行时间。
string[] values = new[] { "1", "2", "3", "1.5", "56.5", "8" };
var file = values.AsParallel()
.Select(s => Double.Parse(s))
.Select(d => (int)Math.Round(d))
.Select(i => Math.Abs(i).ToString())
.ToArray();
关于c# - 仅转换特定值的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24024290/