Linq和总和

时间:2012-09-04 13:51:49

标签: c# linq sum

下面有一段简单的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqStuff
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var aS = new List<A>();
            aS.Add(new A { aId = 0 });
            aS.Add(new A { aId = 1 });

        var bs = new List<B>();
        bs.Add(new B { aId = 0, bId = 0 });
        bs.Add(new B { aId = 0, bId = 1 });

        var cs = new List<C>();
        cs.Add(new C { bId = 0, cId = 0, Val = 100 });
        cs.Add(new C { bId = 0, cId = 1, Val = 100 });
        cs.Add(new C { bId = 1, cId = 2, Val = 100 });
        cs.Add(new C { bId = 1, cId = 3, Val = 100 });


    }
}

internal class A
{
    public int aId { get; set; }
}

internal class B
{
    public int aId { get; set; }
    public int bId { get; set; }
}

internal class C
{
    public int bId { get; set; }
    public int cId { get; set; }
    public int Val { get; set; }
}

}

我想做的是让alinq能够带回我这样的2个匿名对象:

首先:(援助= 1,总和= 0) 第二:(援助= 0,总和= 400)

Sum是通过B与A链接的所有对象C的总和。

我尝试过使用SelectMany但是我从来没有比回到5对(A,C)我需要稍后执行分组更进一步。

E.g。

            var result = aS.SelectMany(a => bs.Where(b => b.aId == a.aId).DefaultIfEmpty(),
                                        (a, b) => new { A = a, B = b })
                            .SelectMany(b => cs.Where(c => b != null && b.B != null && c.bId == b.B.bId).DefaultIfEmpty(),
                                        (b, c) => new { A = b.A, C = c })

有些东西不见了,你能帮我吗?

干杯。

2 个答案:

答案 0 :(得分:2)

不是最美丽的Linq声明,但是应该这样做;

var result = aS.Select(a => 
  new { a.aId, 
        sum = cs.Where(c => bs.Where(b => b.aId == a.aId)
                .Select(b => b.bId)
                .Contains(c.bId))
                .Sum(c => c.Val) 
      }).ToList();

答案 1 :(得分:0)

var results = from a in aS
              let matchingBIds = bS.Where(b => b.aId == a.aId).Select(b => b.bId)
              let matchingCs = cS.Where(c => matchingBIds.Contains(c.bId))
              let Sum = matchingCs.Sum(c => c.Val)
              select new { a.aId, Sum };