10

I have two tables

TableA
aId
aValue

TableB
bId
aId
bValue

I want to join these two tables via aId, and from there, group them by bValue

var result = 
from a in db.TableA
join b in db.TableB on a.aId equals b.aId
group b by b.bValue into x
select new {x};

My code doesn't recognize the join after the group. In other words, the grouping works, but the join doesn't (or at least I can't figure out how to access all of the data after the join).

ekad
  • 14,436
  • 26
  • 44
  • 46
sooprise
  • 22,657
  • 67
  • 188
  • 276

2 Answers2

22

The expression between the group and the by creates the group elements.

var result =  
from a in db.TableA 
join b in db.TableB on a.aId equals b.aId 
group new {A = a, B = b} by b.bValue;

  // demonstration of navigating the result
foreach(var g in result)
{
  Console.WriteLine(g.Key);
  foreach(var x in g)
  {
    Console.WriteLine(x.A.aId);
    Console.WriteLine(x.B.bId);
  }
}
Amy B
  • 108,202
  • 21
  • 135
  • 185
0

Your result object will be an IQueryable<IGrouping<T>>, so you'd have to access one of the results collection, which will be IGrouping<T>, and then dig into that collection to get the x objects.

Jay
  • 56,361
  • 10
  • 99
  • 123