【问题标题】:linq to lambda expressionlinq 到 lambda 表达式
【发布时间】:2011-08-29 10:30:48
【问题描述】:

我正在尝试将下面的代码转换为 lambda 表达式

from b in bookResults
group b by new { b.Title1, b.Pubs_id, b.Notes } into g
select new XElement("book",
new XAttribute("pub_id", g.Key.Pubs_id), new XAttribute("note", g.Key.Notes),
new XElement("Title", g.Key.Title1),
from bk in g
select new XElement("Name", new XAttribute("au_id", bk.Au_id), bk.Name))));

lambda 表达式

bookResults.GroupBy(g => new { g.Title1, g.Pubs_id, g.Notes })
           .Select(group => new XElement("book", 
                                         new XAttribute("pub_id",
                                                        group.Key.Pubs_id),
                                         new XAttribute("note", group.Key.Notes),
                                         new XElement("Title", group.Key.Title1)))
                           **.Select(bk => new XElement("Name",
                                                        new XAttribute("au_id",
                                                                       bk.Au_id),
                                                        bk.Name)**)));

我的问题在于第二个选择,因为我不知道如何将它与
(来自 g 中的 bk)

【问题讨论】:

  • 这不是 lambda 表达式。这是方法调用语法中的 LINQ 查询。 lambda 表达式就像x => blah

标签: .net linq linq-to-xml


【解决方案1】:

这部分只是另一个常规查询,从上一个选择的 lambda 参数开始:

bookResults.GroupBy(g => new { g.Title1, g.Pubs_id, g.Notes })
     .Select(group => new XElement("book", 
                 new XAttribute("pub_id", group.Key.Pubs_id),
                 new XAttribute("note", group.Key.Notes),
                 new XElement("Title", group.Key.Title1)),
                 // "from bk in g select" becomes "g.Select(bk =>"
                 // but here you're using group as the parameter name
                 group.Select(bk => new XElement("Name",
                      new XAttribute("au_id", bk.Au_id), bk.Name))));

【讨论】:

    猜你喜欢
    • 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
    相关资源
    最近更新 更多