C# lambda expression question - how to join 2 tables using Lambda statements from the following SQL?

17,435

Solution 1

If you mean method syntax and not query syntax of linq then you can do

var results = context.boards.Where(b => b.bid == 1)
                            .DefaultIfEmpty()
                            .Join(context.categories, 
                                  b => b.bid,
                                  c => c.cid,
                                  (b, c) => c);

Solution 2

You can use a group join like:

var qry = boards.GroupJoin(
    categories,
    b => b.CategoryID,
    c => c.CategoryID,
    (x, y) => new { Board = x, Categories = y })
    .SelectMany(
    x => x.Categories.DefaultIfEmpty(),
    (x, y) => new { Board = x.Board, Category = y });
Share:
17,435

Related videos on Youtube

Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I have 2 tables, and I would like to join them using Lambda statements (not Linq but Lambda).

    This is the query that I need:

    SELECT
        c.*
    FROM
        board as b
    LEFT JOIN category as c ON
        b.cid = c.cid
    WHERE
        b.bid = 1
    

    How do I do this?

    Say if board is a dataset/variable and category is an other dataset/variable then i want somethign like board.Join(category).Where(b=>b.bid==c.cid) ( i know this is wrong but just so you have an idea what i am looking for thank you so much for all your help

    • Chris Eberle
      Chris Eberle almost 13 years
      SQL doesn't have lambda expressions.
    • Admin
      Admin almost 13 years
      i want the C# lambda expression for the following SQL this SQL is just an example all i want to know is how to join 2 datasets using Lambda Expressions
    • Saint
      Saint almost 13 years
      Maybe look at this thread?
    • Chris Eberle
      Chris Eberle almost 13 years
      You've given nothing to work with. What have you tried? Give some examples.
    • Admin
      Admin almost 13 years
      why is my post down graded? :(
    • Tom H
      Tom H almost 13 years
    • philiphobgen
      philiphobgen almost 13 years
      @Kathy - look at @Bala R's answer. It's probably what you want. You may have understood what lamda expressions are. They're only part of the puzzle for you - in your edit above only "b=>b.bid==c.bid" is a lambda, the rest is method syntax.... Take a look at this link: msdn.microsoft.com/en-us/library/bb397947.aspx HTH
    • FlyingStreudel
      FlyingStreudel almost 13 years
      Why downvote this? Its a valid question, just a dupe. Theres a nifty button you can press to mark it as a dupe that isn't the down arrow.
  • FlyingStreudel
    FlyingStreudel almost 13 years
    It joins two collections and groups the results, so in this case you would get the group where a board has no corresponding category. msdn.microsoft.com/en-us/library/…