Method vs Linq based query syntax example

I need to make inner join on 3 tables; LedgerTypes, LedgerControl and Ledger.

Method based query example

//method based query
// your starting point - table in the "from" statement
var list = LedgerTypes
  //the source table of the inner join
     //primary key (first part of sql "join" statement)
     t => t.Id,
     //foreign key (the second part of the "on" clause)
     lc => lc.ControllerTypeId, 
  (t, lc) => new { t, lc })   //new join
  // third table in the join clause
    //third table foreign key
    tc =>, 
    //second table primary key
    l => l.ControllerID, 
  (tc, l) => new { tc, l })
      .Select(result => new {          //selection
       LedgerTypeId =,
       LedgerTypeName =,
       LedgerControlId =,
       LedgerControlName =,
       LedgerId =,
       LedgerName =
       // other assignments

Linq based query example

 //linq based query
var list = from t in LedgerTypes
    join lc in LedgerControl on t.Id equals lc.ControllerTypeId
    join l in Ledger on lc.Id equals l.ControllerID
    select new
             LedgerTypeId = t.Id,
             LedgerTypeName = t.ControllerTypeName,
             LedgerControlId = lc.Id,
             LedgerControlName = lc.ControllerCodeFullName,
             LedgerId = l.Id,
             LedgerName = l.LedgerCodeFullName
            // other assignments

I prefer query syntax because it’s readable and maintainable.


For more info read here and here

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect