tags:

views:

90

answers:

7

I basically have a lot of poorly designed code to do something that, I'm sure, can be done far more elegantly.

What I'm trying to do is grab the last date from a database table.

var Result = 
from a in DB.Table
orderby a.Date descending
select new {Date = a};

foreach(var Row in Result)
{
LastDate = Row.Date.Date;
break;
}

Basically, there's a foreach loop that is designed to run only once. Crappy code! What's a "best practice" way to accomplish the same thing?

+7  A: 

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.

SLaks
+12  A: 
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.

Cylon Cat
+2  A: 
var LastDate = DB.Table.OrderBy(a => a.Date).FirstOrDefault();
moi_meme
A: 

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

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

jim
A: 

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.

SWeko
He doesn't want an `IEnumerable`.
SLaks
A: 

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

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

Ralph Shillington
Only if you first write `.Cast<DateTime?>`
SLaks
A: 

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)
Stuart Lange