views:

22

answers:

3

i have code

public List<Files> List(int? menuId)
{
    if (menuId == null)
    {
        return _dataContext.Files.ToList();
    }
    else
    {
        return _dataContext.Files.Where(f => f.Menu.MenuId == menuId).ToList();
    }
}

is it possible to make it only one line like return _dataContext.Files.Where(f => f.Menu.MenuId == menuId).ToList();?

+1  A: 
public List<Files> List(int? menuId) {
    return _dataContext.Files.Where(f => menuId == null || f.Menu.MenuId == menuId).ToList();
}
strager
A: 

Just use the "logical OR" operator (||) :

public List<Files> List(int? menuId)
{
    return _dataContext.Files.Where(f => !menuId.HasValue || f.Menu.MenuId == menuId).ToList();
}
Thomas Levesque
A: 

Sure, you can put the null check inside the lambda function:

return _dataContext.Files.Where(f => menuId == null || f.Menu.MenuId == menuId.Value).ToList();

However, if performance is any concern then your original version is preferable, because this version would unnecessarily call .Where() when menuId is null. (It would probably be a negligible difference in most cases, though.)

Evgeny