Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take all in ternary operator in LINQ?

Consider this function :

public List<Employees> getEmployees(....... , int? takeMax = null)
{
    // some code 
    ...

    var items = DB_Context.Employees.Where(%%%%% WHATEVER %%%%).Take(takeMax.HasValue && takeMax.Value > 0 ? takeMax.Value :  ?????? ).ToList();
}

How can I take all the items in case takeMax is NULL?

The Take() takes int , and I don't want to write something like

int total = DB_Context.Employees.Count();
var items = DB_Context.Employees.Where(%%%%% WHATEVER %%%%).Take(takeMax.HasValue && takeMax.Value > 0 ? takeMax.Value :  total ).ToList();

Any alternative ?

like image 376
JAN Avatar asked Mar 14 '23 13:03

JAN


1 Answers

You could only apply the take in that case:

var itemsQuery = DB_Context.Employees.Where(%%%%% WHATEVER %%%%);
if (takeMax > 0)
{
  itemsQuery  = itemsQuery.Take(takeMax);
}

var items = itemsQuery.ToList();
like image 91
TomDoesCode Avatar answered Mar 25 '23 06:03

TomDoesCode