views:

91

answers:

3

Ok,

I have a LinqToXml query that returns a single record (correct terminology?),

however, I don't want to use a for.. loop to pull that one record from the query. Is there an easier way?

*bonus if you find a better way to write the query (I'm still learning)

my xml file:

<?xml version="1.0"?>
<!-- first draft of LibMappings.xml file -->
<LibMappings>
    <File>
     <Name>Foundation.dll</Name>
     <Map>Lib\Foundation</Map>
    </File>
</LibMappings>

My Code:

private static string GetMapFor(string dllName)
{
        //Opens Xml File and gets "Lib" map for dllName
        string retVal;
    XDocument libMapFile = XDocument.Load(_libMapFilePath);

    //This query will return 1 record
    IEnumerable<XElement> query = from c in libMapFile.Descendants("File")
                   where (string)c.Element("Name") == dllName
                  select c.Element("Map");
    if (query.Count() == 1)
    {
     //there's only gonna be one here.. I might as well do this..
     foreach (string x in query)
     {
      retVal = x;
      break;
     }

     //I'd like to do this:
     retVal = query[0];

    }
     return retVal;
}
+1  A: 
IEnumerable<XElement> query = from c in libMapFile.Descendants("File")
                                        where (string)c.Element("Name") == dllName
                                select c.Element("Map");
XElement element = query.First();
return element.Value;
Hamish Smith
A: 

Hi,

Try this:

select c.Element("Map").First();

or, if you're not sure you'll get as result:

select c.Element("Map").FirstOrDefault();

then check for null to see if you have a result.

Daniel M
+4  A: 

You are either looking for the First or FirstOrDefault extension method.

These methods will return the first element int the query. They only differ in behavior when the query result is empty. The First method will throw an exception while FirstOrDefault will return the default value for the type of element in the query (typically null).

var first = query.First();
JaredPar