【问题标题】:Better way to calculate the SUM of one, two and three consecutive items计算一个、两个和三个连续项目的总和的更好方法
【发布时间】: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 个值。

标签: c# sql linq sum


【解决方案1】:

缓慢的根本原因是您的循环是 O(n^2),因为对于每个元素,您都在整个列表中搜索其后继者。下面将其减少到 O(n log n) (最慢的部分是排序)。

List<myItem> list;
list.Sort(<.. sort by id ..>);
for (int i = 0; i < list.Count; i++)
{
   myItem m = list[i];
   m.Sum1 = m.Value;

   m.Sum2 = m.Sum1;
   if (i < list.Count - 1)
   {
       m.Sum2 += list[i + 1].Value;
   }

   m.Sum3 = m.Sum2;
   if (i < list.Count - 2)
   {
       m.Sum3 = += list[i + 2].Value;
   }
}

【讨论】:

  • 使用Count 属性,而不是Enumerable.Count() 扩展方法。另外,你的第二个if 应该是-2,对吗?
  • 好的。我看到你做了什么,只需要一些改变,因为最后一行需要{21, 21 + 0, 21 + 0 + 0 }
  • @Eris:虽然我同意使用Count 属性,但值得注意的是Enumerable.Count() 将在源为ICollection&lt;T&gt; 时使用Count 属性。跨度>
【解决方案2】:

只是对 Jared 的解决方案进行了一些修改,但使用了他的想法:

        List<myItem> list;
        //list.Sort(<.. sort by id ..>);
        int count = list.Count();
        for (int i = 0; i < count; i++)
        {
            myItem m = list[i];
            m.Sum1 = m.Value;                
            m.Sum2 = (i+1 < count) ? (m.Value + list[i+1].Value) : m.Value;
            m.Sum3 = (i+2 < count) ? (m.Sum2 + list[i+2].Value) : m.Sum2;                
        }

【讨论】:

  • 正如@eris 所说。不要使用list.Count() 方法,只需调用list.Count 属性即可。
  • 抱歉忘记了。
【解决方案3】:

(取消删除答案,因为事实证明其他答案仍然存在细微的错误)

LINQ 在这方面没有帮助您。只需根据需要引用数组索引:

List<myItem> list;

// sort list by id
list.Sort(t => t.ID);

for (int i = 0; i < list.Count; i++)
{
   myItem m = list[i];

   m.Sum1 = m.Value;
   m.Sum2 = m.Sum1 + (i + 1 < list.Count ? list[i + 1].Value : 0);
   m.Sum3 = m.Sum2 + (i + 2 < list.Count ? list[i + 2].Value : 0);
}

编辑:关于 list.Count() 与 list.Count 的小旁注

我注意到有些 cmets 不使用 list.Count() (Enumerable.Count()) 来支持 list.Count(属性)。我个人也喜欢这样,但应该注意的是,与某些人可能会相信的不同,Enumerable.Count() 版本 不会 迭代整个列表以获取计数。相反,因为它检测到列表是ICollection&lt;T&gt; 的实现,所以它将直接使用Count 属性。所以说真的,在这种特定情况下这两个选项之间的性能差异可以忽略不计。

此行为已记录在 here。

如果 source 的类型实现了ICollection&lt;T&gt;,则该实现用于获取元素的计数。否则,此方法确定计数。

【讨论】:

  • 您还必须按 id 对数组进行排序。
  • @Jared:糟糕,错过了。
【解决方案4】:

另一种解决方案。不需要排序。不确定它是否会运行得更快,请检查。

list.ForEach(m =>
{
      m.Sum1 = m.Value;
      m.Sum2 = ((m.ID + 1) < list.Count) ? (m.Sum1 + list[m.ID + 1].Value) : m.Sum1;
      m.Sum3 = ((m.ID + 2) < list.Count) ? (m.Sum2 + list[m.ID + 2].Value) : m.Sum2;
});

【讨论】:

    【解决方案5】:

    这里的功能方式:

    var seed = new { 
        Result = new List<myItem>(), 
        Item1 = ( myItem )null, 
        Item2 = ( myItem )null 
    };
    // seed contains intermediate result and other items related to currentItem
    // [Item1, Item2, currentItem]
    // For the first item, it would be
    // [null, null, Id = 1]
    // For the second item, it would be
    // [null, Id = 1, Id = 2]
    // And the third
    // [Id = 1, Id = 2, Id = 3]
    // For nth item, it's
    // [Id = n-2, Id = n-1, Id = n]
    var final = input.Aggregate( seed, ( pr, i ) =>
    {
        if ( pr.Item1 != null )
        {
            var item1 = pr.Item1;
            item1.Sum3 = item1.Sum2 + i.Value;
        }
    
        if ( pr.Item2 != null )
        {
            var item2 = pr.Item2;
            item2.Sum2 = item2.Sum1 + i.Value;
        }
    
        pr.Result.Add( i );
        i.Sum1 = i.Value;
        // It will create lots of short life object.
        // If performance is bad, create named class just as this anonymous class,
        // update its properties and return it
        // pr.Item1 = pr.Item2;
        // pr.Item2 = pr.i;
        // return pr;
        return new { Result = pr.Result, Item1 = pr.Item2, Item2 = i };
    } );
    

    【讨论】:

    • 好吧,看来是在正确的轨道上,但你需要添加一些解释。不确定您如何引用下一项
    • 它不引用下一项,但如果有前两项,则引用前两项。
    • input.Aggregate 是什么?
    猜你喜欢
    • 2016-10-12
    • 2022-12-22
    • 1970-01-01
    • 2016-03-27
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多