日期:2014-05-17 浏览次数:20769 次
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