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

时间:2012-12-03 21:27:21

标签: linq join lambda

似乎大多数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 };

2 个答案:

答案 0 :(得分:15)

我更喜欢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}

时:

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

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

答案 1 :(得分:7)

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});