4

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 ?

haim770
  • 48,394
  • 7
  • 105
  • 133
JAN
  • 21,236
  • 66
  • 181
  • 318

3 Answers3

4

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();
TomDoesCode
  • 3,580
  • 2
  • 18
  • 34
3

This is a way, where you still have to write two lines (like your example of taking count), but you do not have to calculate Count.

var query = DB_Context.Employees.Where(%%%%% WHATEVER %%%%);
var items = takeMax.HasValue && takeMax.Value > 0 ? 
                query.Take(takeMax.Value).ToList() : query.ToList();
Arghya C
  • 9,805
  • 2
  • 47
  • 66
0

Maybe like this:

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


...

if(takeMax != null)
{
    return DB_Context.Employees.Where(%%%%% WHATEVER %%%%).Take(takeMax).ToList();
}
else
{
    return return DB_Context.Employees.Where(%%%%% WHATEVER %%%%).ToList();
}
MajkeloDev
  • 1,661
  • 13
  • 30