1

I have a methods that takes multiple arrays and filter data using linq, the problem I am having is that one or more arrays could be null and I am not sure how to handle null arrays in Linq.:

public IPagedList<SGProduct> GetFilteredProducts(string catID, string[] houseID, int page = 1)
        {
            return MongoContext.Products.AsQueryable<SGProduct>().AsEnumerable().Where(x =>houseID.Contains(x.HouseID.ToString()) && x.ProductCategoryID.ToString() == catID).ToList().ToPagedList(page, 6);
        }

The houseID array could be null also I will have more parameters to this method like Size array etc.

Any suggestions. Thanks

1 Answer 1

1

Just add null check for array, end create empty one if it's null.

public IPagedList<SGProduct> GetFilteredProducts(string catID, string[] houseID, int page = 1)
{
    if(houseID == null) houseID = new string[] {};
    return MongoContext.Products.AsQueryable<SGProduct>().AsEnumerable().Where(x =>houseID.Contains(x.HouseID.ToString()) && x.ProductCategoryID.ToString() == catID).ToList().ToPagedList(page, 6);
}

Also, you can query variable and build it with conditions as you go. And then you have finished, just materialize and return records.

public IPagedList<SGProduct> GetFilteredProducts(string catID, string[] houseID, int page = 1)
{
    var query = MongoContext.Products.AsQueryable<SGProduct>();
    if(houseID == null)
        query = query.Where(x =>houseID.Contains(x.HouseID.ToString()) && x.ProductCategoryID.ToString() == catID);

    return query.ToList().ToPagedList(page, 6);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.