tags:

views:

542

answers:

1

I am trying to use the C# Linq query Descendants method using variables. Here is part of the XML

<CourseList>
    <course id="EM220" name="Fundamentals of Mechanics"/>
    <course id="EM305" name="Engineering Tools Seminar"/>
    <course id="EM320" name="Dynamics"/>
</CourseList>

Here is the query:

static void GetAllCourseIds(XElement doc)
{
    IEnumerable<XElement> courseId =
         from ci in doc.Descendants("course") <---want to use a variable
         select ci;
    foreach (XElement ci in courseId)
        Console.WriteLine((string)ci.Attribute("id"));
}

I tried to use

string c = "course";

then replaced

from ci in doc.Descendants("course")

with

from ci in doc.Descendants(c)

It would seem easy to do , but obviously not.

any suggestions?

A: 

That should work absolutely fine. Note that there's no need to use a query expression here - you can just use:

static void GetAllCourseIds(XElement doc, string elementName) 
{ 
    IEnumerable<XElement> courseId = doc.Descendants(elementName);
    foreach (XElement ci in courseId)
    {
        Console.WriteLine((string)ci.Attribute("id"));
    }
}

If that doesn't work for you for some reason, please say what goes wrong. (That's always a good idea when asking a question.)

Jon Skeet