开发者

Grabbing Just The Top Entry From A LINQ Query

开发者 https://www.devze.com 2023-01-03 15:03 出处:网络
I basically have a lot of poorly designed code to do something that, I\'m sure, can be done far more elegantly.

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 descend开发者_StackOverflow社区ing
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?


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
    ).First();

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号