'Using LINQ to select the last record in .NET Framework

I need to query for the last record in a SQL database, utilizing LINQ. The way I am doing it now takes two steps. First, I get the ID value with a OrderByDescending. then, I use the ID in another query to get the complete record set.

var model = _context.SystemViewModel.OrderByDescending(u => u.ID).Select(x => x.ID).FirstOrDefault();

if (ID > 0)
{
    ViewBag.user = from x in _context.SystemViewModel where x.ID == ID select x;
}
else
{
    ViewBag.user = from x in _context.SystemViewModel where x.ID == model select x;
}

IS there a way in LINQ to do this in one step?



Solution 1:[1]

ViewBag.user = from x in _context.SystemViewModel where x.ID == (ID > 0 ? ID : model) select x;

You can use ?:operator https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DamnScandalous