gpt4 book ai didi

c# - 仅转换特定值的有效方法

转载 作者:太空宇宙 更新时间:2023-11-03 18:07:35 25 4
gpt4 key购买 nike

所以假设我有一个字符串数组:

string[] values = new[] { "1", "2", "3", "1.5", "56.5", "8" };

假设我必须遍历这些值并执行以下操作:
  • 将它四舍五入到最接近的偶数(如果它只是 double 数)
  • 四舍五入后删除数字的小数部分。
  • 如果数字为负数,请删除符号。

  • 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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com