Reputation: 173
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
Upvotes: 1
Views: 1509
Reputation: 2228
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);
}
Upvotes: 1