此查询表达式的等效 lambda 表达式

发布于 2024-09-26 08:45:01 字数 580 浏览 1 评论 0原文

根据帖子 使用 linq to xml 选择具有给定属性的元素 等效的 lambda 表达式是什么。

下面的解决方案工作正常

var artistsAndImage = from a in feed.Descendants("artist")
                      from img in a.Elements("image")
                      where img.Attribute("size").Value == "big"
                      select new { Name = a.Element("Name").Value
                                 , Image = img.Value};

我尝试了 lambda 表达式,但它不起作用:-( 有人可以建议等效的 lambda 表达式吗?

As per post Select element with given attribute using linq to xml what will be the equivalent lambda expression.

The below solution works fine

var artistsAndImage = from a in feed.Descendants("artist")
                      from img in a.Elements("image")
                      where img.Attribute("size").Value == "big"
                      select new { Name = a.Element("Name").Value
                                 , Image = img.Value};

I tried the lambda expression but it's not working :-(
can somebody suggest the equivalent lambda expression.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

戴着白色围巾的女孩 2024-10-03 08:45:01

当然:(

var artistsAndImage = feed.Descendants("artist")
                          .SelectMany(a => a.Elements("image"),
                                      (a, img) => new { a, img })
                          .Where(z => z.img.Attribute("size").Value == "big")
                          .Select(z => new { Name = z.a.Element("Name").Value,
                                             Image = z.img.Value });

未经测试,但我认为它应该可以工作。)

这里棘手的一点是第二个 from 子句调用 SelectMany 并引入一个透明标识符 我通过将其称为 z 来降低透明度。

您想在这里避免查询表达式语法有什么特殊原因吗?在这个例子中它更简单 - 我只使用我正在编写的查询中更简单的一个。

Sure:

var artistsAndImage = feed.Descendants("artist")
                          .SelectMany(a => a.Elements("image"),
                                      (a, img) => new { a, img })
                          .Where(z => z.img.Attribute("size").Value == "big")
                          .Select(z => new { Name = z.a.Element("Name").Value,
                                             Image = z.img.Value });

(Untested, but I think it should work.)

The tricky bit here is that the second from clause calls SelectMany and introduces a transparent identifier which I've made somewhat less transparent by calling it z.

Any particular reason you want to avoid query expression syntax here though? It's simpler in this example - I just use whichever is simpler for the query I'm writing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文