求list集合中,名称相同的相邻记录间的累计运算,语句怎么写?

数据库里读出的数据tolist()后,如下表


CId     时间          合计数量    
1    2021-9-1                 10         
1    2021-9-5                 20          
1    2021-9-11               -5        
2    2021-9-15                5           
2    2021-9-20               -5        
2    2021-9-20               10  
3    2021-9-21               10  

希望得到的结果集如下

CId     时间            累计数量    
1    2021-9-1                10         
1    2021-9-5                30          
1    2021-9-11              25       
2    2021-9-15               5           
2    2021-9-20               0       
2    2021-9-20              10  
3    2021-9-21              10  

请问如何将名称相同的相邻两个记录间,合计数量相加显示在对应的累计数量中

开胃菜:sql开窗统计本身可以
https://www.cnblogs.com/Lumia1020/p/5439982.html

回到你的题目,我们其实很多种方式完成,不过为了不引入其他方式,我们就用最传统的方式完成

static IEnumerable<T> test<T,Tkey>(IEnumerable<T> lst, Func<T, Tkey> func, Func<T, T, T> funm)
        {
            var l = lst.GroupBy(func);
            foreach (var grouping in l)
            {
                var r = test1(grouping, funm);

                foreach (var item in r)
                    yield return item;
            }
        }

        static IEnumerable<T> test1<T>(IEnumerable<T> lst, Func<T, T, T> func)
        {

            T temp = lst.First();
            yield return temp;

            foreach (var x1 in lst.Skip(1))
            {


                temp = func(temp, x1);

                yield return temp;
            }
        }
 List<A> list = new List<A>();
            list.Add(new A() { id = 1, name = "a", value = 10 });
            list.Add(new A() { id = 1, name = "a1", value = 20 });
            list.Add(new A() { id = 1, name = "a2", value = -5 });
            list.Add(new A() { id = 2, name = "a3", value = 5 });
            list.Add(new A() { id = 2, name = "a4", value = -5 });
            list.Add(new A() { id = 2, name = "a5", value = 10 });
            list.Add(new A() { id = 3, name = "a6", value = 10 });
            var resault = test(list,p=>p.id, (a1, a2) =>
            {
                a2.value = a1.value + a2.value;
                return a2;
            }).ToList();

            foreach (var a in resault)
            {
                Console.WriteLine($"{a.name}\t{a.value}");
            }


既然你是从数据库里读出来的,为什么不直接在sql层面上sum好呢

for(int i=0;i<list.count;i++)
{
if(i>0 && list[i]==list[i-1])
{
list.removeAt(i);
list1[i-1]+=list1[i];
list1.removeAt(i);
i--;
}
}