Bastien Vandamme
Bastien Vandamme

Reputation: 18465

Linq to Xml, is it possible to improve this query?

I am trying to learn LINQ to XML. I can not write a query correctly. What should I write to retrieve the list of code of the index MCCO?

<Indexes>
    <Index Name="ARTP">
        <Codes>
            <Code>aaa</Code>
            <Code>bbb</Code>
        </Codes>
    </Index>
    <Index Name="MCCO">
        <Codes>
            <Code>ccc</Code>
            <Code>ddd</Code>
        </Codes>
    </Index>
    <Index Name="AWAY">
        <Value>eee</Value>
    </Index>
</Indexes>

I already wrote this but I feel there is a way to improve query. I assume the fact there are codes (and not values) in my node.

    private List<string> GetCodes(string name)
    {
        var indexes = from index in indexXmlDocument.Descendants("Index")
                      where index.Attribute("Name").Value == name
                      select new 
                      {
                          Codes = index.Element("Codes").Elements("Code")
                      };
        List<string> codes = new List<string>();
        foreach (var code in indexes.Single().Codes)
        {
            codes.Add(code.Value);
        }
        return codes;
    }

Upvotes: 2

Views: 198

Answers (1)

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68687

private IEnumerable<string> GetCodes(string name)
{
    return indexXmlDocument.Descendants("Index")
        .Where(e => e.Attribute("Name").Value == name)
        .Descendants("Code")
        .Select(e => e.Value);
}

Upvotes: 5

Related Questions