tags:

views:

65

answers:

2

I'm working with a XML file that looks something like this:

<lfm status="ok">
    <user>
       <name>JohnnyWestlake</name>
       <image size="large">http://someurl.com/large.jpg&lt;/image&gt;
       <image size="extralarge">ttp://someurl.com/exlarge.jpg</image>
       ...
    </user>
</lfm>

And I'm adding this to a user class using Linq like so:

        User user;

        user = (from lfmUser in userrequest.Descendants("user")
               select new User
               {
                   Name = lfmUser.Element("name").Value,
                   ImageM = lfmUser.Element("image").Value,
                   ...
               }).FirstOrDefault();

Question, how can I set ImageM to the url contained in image size="extralarge", and not image size="large"? Or should I go about it another way?

+3  A: 
ImageM = lfmUser.Elements("image")
                .Where( e => e.Attribute( "size" ).Value == "extralarge" )
BioBuckyBall
i voted up your solution even if it's better to use firstordefault instead of 'first()'
frabiacca
@frabiacca I actually removed it, but 'better' depends on the situation. If you REQUIRE a value for whatever your are 'Firsting', then using FirstOrDefault may not be better, maybe you would rather have the exception. NuclearWinter nw = new ABomb( accessCode.FirstOrDefault() ).Detonate(); // what happens now??
BioBuckyBall
@Lucas: i wrote 'better' because i thought that if i have to extract some text from my xml i expect something in output. If you use First() it will throw an InvalidOperationException if the sequence does not contain any value.
frabiacca
Thanks both for your answers, works like a charm, much appreciated =)
Johnny Westlake
@frabiacca Correct. I'm saying the exception is exactly what you want sometimes, and getting Default(T) is what you want other times. Neither is better all the time, the programmer has to decide based on the situation. :)
BioBuckyBall
Just one small thing to make this better would be to use explicit conversion operator instead of .Value (http://www.hanselman.com/blog/ImprovingLINQCodeSmellWithExplicitAndImplicitConversionOperators.aspx)
Necros
A: 

Try this:

var user = (from lfmUser in userrequest.Descendants("user")
    select new User
    {
        Name = lfmUser.Element("name").Value,
        ImageM = lfmUser.Descendants("image").Where(x=>x.Attribute("size").Value == "large").First().Value
    }).FirstOrDefault();
Rob