Home > OS >  Using LINQ to select the last record in .NET Framework
Using LINQ to select the last record in .NET Framework

Time:05-20

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?

CodePudding user response:

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

  •  Tags:  
  • linq
  • Related