Below have a simple piece of code:
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; }
}
}
What i would like to do is to have alinq that will bring me back 2 anonymous objects like this:
First: (aid = 1, Sum = 0)
Second: (aid = 0, Sum = 400)
The Sum is the sum of all objects C that are linked through B with A.
I tried with SelectMany but I never get further than getting back 5 pairs of (A, C) that i need to perform grouping on later.
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 })
Something is missing, could you please help me?
Cheers.
Not the most beautiful Linq statement, but this should do it;