Capturing only the top record from a LINQ query

I basically have a lot of poorly designed code to do something that, I am sure, can be made much more elegant.

What I'm trying to do is grab the latest 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 is a foreach loop that is designed to run only once. Shitty code! What is the best practice way to do the same thing?

+3
source share
7 answers
var first = Result.First();

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

+13
source

Challenge First().
For instance:

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

, FirstOrDefault(), DateTime.MinValue , .

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

FirstOrDefault() LastOrDefault() ... ...

[] - , :)

+1

Result.Take(1) Take(1) First() , First , Take IEnumerable .

0

Date , coalesce.

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

0

, "" (, , linq2sql SQL MAX):

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

Source: https://habr.com/ru/post/1749937/


All Articles