Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a foreach to run once

Tags:

c#

foreach

xml

So the question is this, I have a for each loop that I am currently using to retrieve data from a query of an XML file which then gets put into a string; like so:

foreach (var value in dateQuery)
                date = value.Element("HistoryCreation").Value;

I know for a fact (Based on the way the xml file stores values and the query being used) that there will only be one value in dateQuery.

Thus, I would like to know (for the purposes of making my program more efficient and learning how to code better), is there a better way to do this or are foreach's the only way?

like image 521
Immanu'el Smith Avatar asked Jun 29 '10 13:06

Immanu'el Smith


1 Answers

You could use:

dateQuery.First().Element("HistoryCreation").Value

This won't fail if there is multiple items in the query. If you want it to fail if there are multiple items, then use Single

like image 165
tster Avatar answered Nov 02 '22 11:11

tster