Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access all of the data after joining two tables and group them using linq

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

like image 217
sooprise Avatar asked May 20 '10 19:05

sooprise


People also ask

How can we do a GroupBy using LINQ query?

You can also use Into Group with GroupBy in VB.Net. LINQ query is ended with the help Select or Groupby clause. It can also support method syntax in both C# and VB.Net languages. As shown in example 2.

What does LINQ GroupBy return?

GroupBy & ToLookup return a collection that has a key and an inner collection based on a key field value. The execution of GroupBy is deferred whereas that of ToLookup is immediate. A LINQ query syntax can be end with the GroupBy or Select clause.

What is LINQ Group join?

In simple words, we can say that Linq Group Join is used to group the result sets based on a common key. So, the Group Join is basically used to produces hierarchical data structures. Each item from the first data source is paired with a set of correlated items from the second data source.

Which join is valid in LINQ?

In LINQ, an inner join is used to serve a result which contains only those elements from the first data source that appears only one time in the second data source.


1 Answers

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);
  }
}
like image 155
Amy B Avatar answered Nov 15 '22 16:11

Amy B