score:13

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.

score:8

Call First().
For example:

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

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

score:3

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

score:1

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

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

score:0

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.

score:0

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

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

score:0

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