tags:

views:

60

answers:

1

As per post http://stackoverflow.com/questions/3885795/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.

+2  A: 

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.

Jon Skeet
its working, just big has to be under "". :-) , no am fine with query expression but just trying the lambda one for learning purpose.and I think I have to go through SelectMany :-)
Wondering
@Wondering: What do you mean by *under ""*? And yes, the equivalent lambda notation will certainly use `SelectMany` as that's what the second `from` translates to.
Jon Skeet
.Where(z => z.img.Attribute("size").Value == "big")
Wondering
@Wondering: Ah, I see what you mean.
Jon Skeet