3

下面有一段简单的代码:

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)更进一步,我需要稍后对其执行分组。

例如

            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 })

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

干杯。

4

2 回答 2

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();
于 2012-09-04T14:07:25.417 回答
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 };
于 2012-09-04T16:17:26.780 回答