More efficient way to build the sum than for a loop

I have two lists with the same size. Both contain numbers. The first list is created, and the second is static. Since I have many of the generated lists, I want to find out which one is better. For me, the best list is the one that best matches the link. Therefore, I calculate the difference in each position and add it.

Here is the code:

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

Is it possible a more elegant, but more important and effective way to get the desired amount?

Thanks in advance!

+1
source share
4 answers

You can do the same with LINQ as follows:

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

, , , . IEnumerable ( IList), .

histDates, , , , .

+5

. , . IList int combinationSum.

histDates.

. .

+1

you can make it more elegant with LINQ, but it will not be more efficient ... if you can calculate the amounts when adding items to the list, you can get an edge ...

0
source

I don’t think I want to guarantee a direct improvement in efficiency, since I can’t test it right now, but it at least looks better:

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

return combination.Select((t, i) => Math.Abs(t - histDates[i].Value)).Sum();
0
source

All Articles