这段话能不能用linq搞定?
循环的话,需要一个变量存“总数”。。能用linq改写吗
List<entity> s = getEntities(); //entity有id字段和qty字段
//想得到一个新集合,元素个数与旧集合一样,新集合有total和id字段,total字段记录旧集合中前n项的qty字段的和
var lst = new List<object>();
decimal totalQty = 0;
foreach (var t in s)
{
totalQty += t.qty;
lst.Add(new {total = totalQty, id = t.id});
}
foreach (var item in lst)
{
...
}
[解决办法]
给本人的解决方案,两行代码搞定
var query = Enumerable.Range(0, s.Count).Select(x => new { total = s.Select((y, i) => new { y, i }).Where(y => y.i <= x).ToList().Select(y => y.y.qty).ToList().Sum(), id = s.ElementAt(x).id }).ToList();
query.ForEach(item=>Console.WriteLine(item.total+" "+item.id));
[解决办法]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Test
{
public int ID { get; set; }
public int QTY { get; set; }
}
class Program
{
static void Main(string[] args)
{
var data = new List<Test>()
{
new Test() { ID = 1, QTY = 3 },
new Test() { ID = 2, QTY = 1 },
new Test() { ID = 3, QTY = 4 },
new Test() { ID = 4, QTY = 2 },
new Test() { ID = 5, QTY = 2 },
new Test() { ID = 6, QTY = 5 }
};
var query = data.Aggregate(new { total = 0, list = new List<Tuple<int, int>>() },
(a, x) =>
{
a.list.Add(new Tuple<int, int>(x.ID, x.QTY + a.total));
return new { total = x.QTY + a.total, list = a.list };
}).list.Select(x => new { total = x.Item2, id = x.Item1 });
foreach (var item in query)
{
Console.WriteLine(item.id + ", " + item.total);
}
}
}
}
1, 3
2, 4
3, 8
4, 10
5, 12
6, 17
Press any key to continue . . .