Accepted answer
var first = Result.First();

If the result set is empty, this will throw an exception; you can use FirstOrDefault() which will return a null if the result set is empty.


Call First().
For example:

LastDate = 
    (from a in DB.Table
     orderby a.Date descending
     select a.Date

If the table might be empty, call FirstOrDefault(), which will return DateTime.MinValue instead of throwing an exception.


var LastDate = DB.Table.OrderBy(a => a.Date).FirstOrDefault();


FirstOrDefault() and as a bonus, you can use LastOrDefault() for... you guessed it...

[edit] -- oh, sudden rush there with the same answer :)


you could also call Result.Take(1) The difference between Take(1) and First() is that First returns a single object, and Take returns an IEnumerable of the type.


If Date is a reference type then you may consider the coalesce operator.

var LastDate = Result.FirstOrDefault() ?? new Date();


If you're trying to find the latest date, you could use the "Max" function (which I believe linq2sql will convert to a SQL MAX operation):

var maxdate = DB.Table.Max(a => a.Date)

Related Articles