比 for 循环更有效的构建总和的方法

本文关键字:构建 和的 方法 有效 for 循环 | 更新日期: 2023-09-27 17:55:17

我有两个大小相等的列表。两者都包含数字。生成第一个列表,第二个列表是静态的。由于我有许多生成的列表,我想找出哪个是最好的。对我来说,最好的列表是最等于参考的列表。因此,我计算每个位置的差异并将其相加。

这是代码:

/// <summary>
/// Calculates a measure based on that the quality of a match can be evaluated
/// </summary>
/// <param name="Combination"></param>
/// <param name="histDates"></param>
/// <returns>fitting value</returns>
private static decimal getMatchFitting(IList<decimal> combination, IList<MyClass> histDates)
{
    decimal fitting = 0;
    if (combination.Count != histDates.Count)
    {
        return decimal.MaxValue;
    }
    //loop through all values, compare and add up the result
    for (int i = 0; i < combination.Count; i++)
    {
        fitting += Math.Abs(combination[i] - histDates[i].Value);
    }
    return fitting;
}

有没有可能有一种更优雅但更重要和更有效的方式来获得所需的金额?

提前感谢!

比 for 循环更有效的构建总和的方法

您可以按如下方式对 LINQ 执行相同的操作:

return histDates.Zip(combination, (x, y) => Math.Abs(x.Value - y)).Sum();

这可以被认为是更优雅的,但它不能比你已经拥有的更有效。它也可以与任何类型的IEnumerable一起使用(因此您不需要特别的IList),但这在您的情况下没有任何实际意义。

如果您手头有此信息,您还可以在运行差异总和大于到目前为止看到的最小总和时立即拒绝histDates

这在不使用列表的情况下是可能的。与其填充两个列表,不如让每个值的总和用于单个列表,例如 IList 组合变为 int combSum

对 histDates 列表执行相同的操作。

然后减去这两个值。在这种情况下不需要循环。

你可以

用 LINQ 做更优雅的事情,但它不会更有效率......如果您可以在将项目添加到列表时计算总和,您可能会获得优势......

我认为我不想保证任何直接的效率提高,因为我现在无法测试它,但这至少看起来更好:

if (combination.Count != histDates.Count)
                return decimal.MaxValue;
return combination.Select((t, i) => Math.Abs(t - histDates[i].Value)).Sum();