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())
: _dataContex开发者_运维技巧t.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: You can think of the where clause as an if
statement.
_dataContext.Ingredients.Where( x => x.Id != null && x.Id == ingredientId)
(Assuming x.Id
is also of type int?
)
Try this:
var preSelect =
_dataContext
.Ingredients
.Where
(
x=> (!ingredientId.HasValue || x.Id == ingredientId)
)
.SelectMany(x=>x.Allergies.AsQueryable());
精彩评论