More efficient way to build sum than for loop

后端 未结 4 1729
暗喜
暗喜 2021-01-24 08:07

I have two lists with equal size. Both contain numbers. The first list is generated and the second one is static. Since I have many of the generated lists, I want to find out wh

相关标签:
4条回答
  • 2021-01-24 08:51

    You can do the same with LINQ as follows:

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

    This could be considered more elegant, but it cannot be more efficient that what you already have. It can also work with any type of IEnumerable (so you don't need specifically an IList), but that does not have any practical importance in your situation.

    You can also reject a histDates as soon as the running sum of differences becomes larger than the smallest sum seen so far if you have this information at hand.

    0 讨论(0)
  • 2021-01-24 08:58

    This is possible without using lists. Instead of filling your two lists you just want to have the sum of each values for a single list, e.g. IList combination becomes int combinationSum.

    Do the same for histDates list.

    Then substract those two values. No loop in this case is needed.

    0 讨论(0)
  • 2021-01-24 09:04

    I don't think I want to garantee any direct improvment of efficiancy as I can't test it right now but this at least looks nicer:

    if (combination.Count != histDates.Count)
                    return decimal.MaxValue;
    
    return combination.Select((t, i) => Math.Abs(t - histDates[i].Value)).Sum();
    
    0 讨论(0)
  • 2021-01-24 09:11

    you can do more elegant with LINQ but it will not be more efficient... if you can calculate the sums while adding the items to the list you might get an edge...

    0 讨论(0)
提交回复
热议问题