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

时间:2013-01-23 12:59:37

标签: c#

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

以下是代码:

/// <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;
}

是否有更优雅但更重要,更有效的方式来获得所需的金额?

提前致谢!

4 个答案:

答案 0 :(得分:5)

您可以使用LINQ执行相同操作,如下所示:

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

这可以被认为更优雅,但它不能比你已经拥有的更有效率。它也适用于任何类型的IEnumerable(因此您不需要专门的IList),但这在您的情况下没有任何实际意义。

如果您手头有这些信息,一旦差异的运行总和大于目前为止看到的最小总和,您也可以拒绝histDates

答案 1 :(得分:1)

这可以不使用列表。您只想获得单个列表的每个值的总和,而不是填充您的两个列表,例如 IList组合变为 int combinationSum

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

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

if (combination.Count != histDates.Count)
                return decimal.MaxValue;

return combination.Select((t, i) => Math.Abs(t - histDates[i].Value)).Sum();
相关问题