日期:2014-05-17  浏览次数:20727 次

这段话能不能用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