开发者

LINQ Where(), what to do if I need to get everything?

开发者 https://www.devze.com 2023-03-11 06:17 出处:网络
Consider the next example: public List<Allergy> GetAllergies(int? ingredientId = null) { var allergies = new List<Allergy>();

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());
0

精彩评论

暂无评论...
验证码 换一张
取 消