More efficient way to build sum than for loop

后端 未结 4 1727
暗喜
暗喜 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.

提交回复
热议问题