【发布时间】:2016-08-11 16:33:40
【问题描述】:
类
public class myItem
{
public int ID;
public long Value;
public long Sum1;
public long Sum2;
public long Sum3;
}
数据
ID Value
1 25
2 45
3 56
4 21
结果:
Sum1 Sum2 Sum3
1 25 25 + 45 25 + 45 + 56
2 45 45 + 56 45 + 56 + 21
3 56 56 + 21 56 + 21 + 0
4 21 21 + 0 21 + 0 + 0
当前程序:工作但非常慢(约 10 分钟),有 100k 行。
List<myItem> list;
for (int i = 0; i < list.Count(); i++)
{
myItem m = list[i];
m.Sum1 = list.Where(x => x.ID == i).Sum(x => x.Value);
m.Sum2 = list.Where(x => x.ID >= i && x.ID <= i + 2).Sum(x => x.Value);
m.Sum3 = list.Where(x => x.ID >= i && x.ID <= i + 3).Sum(x => x.Value);
}
所以我想应该有一种方法可以在没有for 的情况下加快速度。
【问题讨论】:
-
list中的项目是否有序?如果不对它们进行排序,只需使用总和m.Sum2 = list[i].Value + list[i+1].Value;的索引,您所要做的就是添加检查i +1和i +2何时大于list的大小。 -
这非常低效,但这不是因为您使用了
for循环。您对每一行使用list.Where(...)三次,它必须为每个查询搜索整个列表。您为什么不直接引用您想要相对于您当前所在的索引i的myItem对象? -
您还为循环的每次迭代调用
list.Count(),如果列表没有改变,提升计数会有所帮助。您也可以通过在末尾添加两个0值来伪造它,转到i - 2,然后删除附加值,因此总和始终为 3 个值。