XMl Linq question

  • Thread starter Thread starter CSharper
  • Start date Start date
C

CSharper

I am trying to find a first element from an xml file using the
following code
XElement t = xml.Descendants("Element").First();

This works fine, but when there is no result set ofcourse the first
method call bombs. I can always split the statement into two and check
if there are any elements available before I pick the first element.
Is it possible to do it in a single statement?

something like the following

from e1 in xml.Decendants("Element")
select top 1;

Thanks.
 
CSharper said:
I am trying to find a first element from an xml file using the
following code
XElement t = xml.Descendants("Element").First();

This works fine, but when there is no result set ofcourse the first
method call bombs. I can always split the statement into two and check
if there are any elements available before I pick the first element.
Is it possible to do it in a single statement?

Use
XElement t = xml.Descendants("Element").FirstOrDefault();
that way t will be the first 'Element' descendant or nul if there is none.
 
Use
   XElement t = xml.Descendants("Element").FirstOrDefault();
that way t will be the first 'Element' descendant or nul if there is none.

Thanks for the help.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top