tags:

views:

43

answers:

1

I'm a LINQ newbie, so the following might turn out to be very simple and obvious once it's answered, but I have to admit that the question is kicking my arse.

Given this XML:

<measuresystems>
  <measuresystem name="SI" attitude="proud">
    <dimension name="mass" dim="M" degree="1">
      <unit name="kilogram" symbol="kg">
        <factor name="hundredweight" foreignsystem="US" value="45.359237" />
        <factor name="hundredweight" foreignsystem="Imperial" value="50.80234544" />
      </unit>
    </dimension>
  </measuresystem>
</measuresystems>

I can query for the value of the conversion factor between kilogram and US hundredweight using the following LINQ to XML, but surely there is a way to condense the four successive queries into a single complex query?

XElement mss = XElement.Load(fileName);

IEnumerable<XElement> ms =
    from el in mss.Elements("measuresystem")
    where (string)el.Attribute("name") == "SI"
    select el;

IEnumerable<XElement> dim =
    from e2 in ms.Elements("dimension")
    where (string)e2.Attribute("name") == "mass"
    select e2;

IEnumerable<XElement> unit =
    from e3 in dim.Elements("unit")
    where (string)e3.Attribute("name") == "kilogram"
    select e3;

IEnumerable<XElement> factor =
    from e4 in unit.Elements("factor")
    where (string)e4.Attribute("name") == "pound" 
        && (string)e4.Attribute("foreignsystem") == "US"
    select e4;

foreach (XElement ex in factor)
{
    Console.WriteLine ((string)ex.Attribute("value"));
}
+2  A: 

This would work, just add them together:

IEnumerable<XElement> ms =
    from el in mss.Elements("measuresystem")
    where (string)el.Attribute("name") == "SI"
    from e2 in el.Elements("dimension")
    where (string)e2.Attribute("name") == "mass"
    from e3 in e2.Elements("unit")
    where (string)e3.Attribute("name") == "kilogram"
    from e4 in e3.Elements("factor")
    where (string)e4.Attribute("name") == "pound" 
        && (string)e4.Attribute("foreignsystem") == "US"    
    select e4;
Steven
@Richard: that's interesting, would you care to elaborate a bit and add your findings to this page? http://stackoverflow.com/questions/2628582/what-are-the-other-new-features-of-c-4-0-after-dynamic-and-optional-parameters
Abel
@Abel: About to delete earlier comment, now having checked the C#3 spec... appears to be a miss-reading of "C# in a Nutshell" (3rd ed) by me :-(
Richard
This works fine (after you replace "pound" with "hundredweight" to correspond to the xml file -- oops).
Cyberherbalist
@Richard: your original comment was about C#4, wasn't it? But still, you say that the comment should indeed be ignored? If so, I'll delete my comment too :)
Abel
@Able: yes, I had missed that C#3 allowed the form of comprehension expression shown here, and assumed it was new in C#4. My deleted comment was based on that faulty assumption.
Richard