8

It seems like most LINQ is written with lambda expressions. How do I go about rewriting this linq using lambda, kinda confusion with the style (especially with joins)?

var responses =
            from c in questionRepository.GetReponses()
            join o in questionRepository.GetQuestions() on
            c.QuestionID equals o.QuestionID
            where c.UserID == 9999
            orderby o.DisplayOrder
       select new { o.QuestionText, c.AnswerValue };
3
  • You don't really need to rewrite it. It's fine as it is, to be honest. Sometimes I use one style and sometimes the other, and this is a case where I'd probably go for the query syntax. From MSDN: As a rule when you write LINQ queries, we recommend that you use query syntax whenever possible and method syntax whenever necessary. Commented Dec 3, 2012 at 21:29
  • 1
    I like this form for JOIN's. With "Lambda Expressions" it requires specifying 4 arguments (plus the receiver) which, while the same as the above, seems more cluttered. Commented Dec 3, 2012 at 21:30
  • Though query syntax is easier for joins, lambda syntax is easier to debug. For details see simple-talk.com/dotnet/.net-framework/… Commented Sep 23, 2015 at 17:53

2 Answers 2

18

I prefer the "LINQ syntax" for Joins as I think it looks cleaner.

In any case, here is how to translate the LINQ-join to the "Lambda Expression"-join.

The translation for:

from a in AA
join b in BB on
a.Y equals b.Y
select new {a, b}

Is:

AA.Join(                 // L
  BB,                    // R
  a => a.Y, b => b.Y,    // L -> join value, R -> join value
  (a, b) => new {a, b})  // L+R result

The other LINQ keywords are much simpler to convert (e.g. OrderBy(u => u.DisplayOrder) and are just "chained together" with .. - give it a go!

Sign up to request clarification or add additional context in comments.

1 Comment

I think you are missing a comma between b => b.Y and (a, b) => new {a, b} I new at this I could be wrong.
9
var responses = questionRepository.GetReponses()
                   .Join(questionRepository.GetQuestions(), 
                         c => c.QuestionID,
                         o => o.QuestionID,
                         (c, o) => new {c, o})
                   .Where(x => x.c.UserID == 99999)
                   .OrderBy(x => x.o.DisplayOrder)
                   .Select(x => new {x.o.QuestionText, x.c.AnswerValue});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.