Consider the next example:
public List<Allergy> GetAllergies(int? ingredientId = null)
{
var allergies = new List<Allergy>();
var preSelect = ingredientId != null
? _dataContext.Ingredients.Where(x=> x.Id == ingredientId).SelectMany(x=>x.Allergies.AsQueryable())
: _dataContext.Allergies.AsQueryable();
preSelect.ToList().ForEach(x =>
{
var a = Mapper.Map<Database.Allergy, Allergy>(x);
allergies.Add(a);
});
return allergies;
}
That works, but I believe it’s possible to get rid of null checking part and get all Ingredients if ingredientId is null right there in Where() body. How can we do that? Also any other suggestions to improve this piece of code will be appreciated.
Try this: