【问题标题】:How to rewrite this LINQ using join with lambda expressions?如何使用带有 lambda 表达式的连接重写此 LINQ?
【发布时间】:2012-12-03 21:27:21
【问题描述】:

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

【问题讨论】:

  • 你真的不需要重写它。老实说,这很好。有时我使用一种风格,有时使用另一种风格,在这种情况下,我可能会选择查询语法。来自MSDNAs a rule when you write LINQ queries, we recommend that you use query syntax whenever possible and method syntax whenever necessary.
  • 我喜欢这种 JOIN 表格。使用“Lambda 表达式”,它需要指定 4 个参数(加上接收者),虽然与上面相同,但看起来更混乱。
  • 虽然查询语法更容易用于连接,但 lambda 语法更容易调试。详情见simple-talk.com/dotnet/.net-framework/…

标签: linq join lambda


【解决方案1】:

我更喜欢 Join 的“LINQ 语法”,因为我认为它看起来更简洁。

无论如何,这里是如何将 LINQ 连接转换为“Lambda 表达式”连接。

翻译:

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) 并且只是与 .“链接在一起”。 - 试试看!

【讨论】:

  • @user166390 这有帮助。
  • 我认为您在 b => b.Y 和 (a, b) => new {a, b} 之间缺少逗号,我是新手,我可能错了。
【解决方案2】:
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});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多