如何使用lambda表达式连接重写此LINQ?

Cha*_*aka 7 linq lambda join

看起来大多数LINQ都是用lambda表达式编写的.我如何使用lambda重写这个linq,有点混淆风格(尤其是连接)?

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 };
Run Code Online (Sandbox Code Playgroud)

小智 16

我更喜欢Joins的"LINQ语法",因为我觉得它看起来更干净.

无论如何,这里是如何将LINQ-join转换为"Lambda Expression"-join.

翻译为:

from a in AA
join b in BB on
a.Y equals b.Y
select new {a, b}
Run Code Online (Sandbox Code Playgroud)

方法是:

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
Run Code Online (Sandbox Code Playgroud)

其他LINQ关键字转换起来要简单得多(例如OrderBy(u => u.DisplayOrder),只是与它们"链接在一起" .. - 试一试!


Ser*_*kiy 8

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});
Run Code Online (Sandbox Code Playgroud)