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

时间:2010-10-08 16:27:59

标签: c# linq-to-xml

根据帖子Select element with given attribute using 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表达式。

1 个答案:

答案 0 :(得分:2)

不确定

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并引入了一个透明标识符,通过调用它{{1}我已经使其变得不那么透明了}。

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