Tutorial :Getting a foreach to run once


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?


You could use:


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


date = dateQuery.Single().Element("HistoryCreation").Value;  


If you are using .NET 3.5 or newer you could use the extension method Enumerable.Single:

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

Then if your assumption 'there will only be one value in dateQuery' is wrong it will throw an exception.


Mark's Answer is by far the best, but I put mine for illustrating foreach loop.

foreach (var value in dateQuery) {      date = value.Element("HistoryCreation").Value;      break;  // break current loop  }  


Emmanual, if you know you only need to do something once, you shouldn't use a loop.


Summing up:

  • use First() if you want the first item and know that there is at least one (or more) items in the sequence.
  • use FirstOrDefault() if the sequence can have any number of items
  • use Single() if the sequence can have exactly one item
  • use SingleOrDefault() if the sequence always has either zero or one item

Note that there are also versions of these which take predicates, so that you can abbreviate

var result = sequence.Where(predicate).First();  


var result = sequence.First(predicate);  


Can't you simply access the first index of dateQuery?

date = dateQuery[0].Element("HistoryCreation").Value;  


Try Enumerable.Single or Enumerable.SingleOrDefault:

 date = dateQuery.Single().Element("HistoryCreation").Value;  



if you are able to use LINQ


You can try

var theValue = dateQuery.FirstOrDefault();  if (theValue != null)  {     data = theValue.Element("HistoryCreation").Value;  }  else  {         //Deal with the fact that there is no data  }  

You could use .First() or .Single(), but if there is nothing in dataQuery an exception will be thrown.


that should do the trick:

using System.Linq;    dateQuery.Single();  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »