Suppose I have the following class and objects:
class Product
{
public int ProductId { get; set; }
public string ProductDesc { get; set; }
}
string[] keywordArray = new string []{"A", "B", "C", "D"};
var products = repository.GetAllProducts();
I use var
because GetallProducts()
returns a IQueryable<Product>
but I cannot "see" the Product
type since it is defined in my DAL.
Now I need a temp variable tempResult
to store temporary results in a foreach
. For example:
foreach(var keyword in keywordArray)
{
tempResult = tempresult.Union(products.Where(p => p.ProductDesc.Contains(keyword)));
}
If I declare var tempResult
inside the foreach
, it is overwritten at each iteration (and it will give a compile time error, because it cannot be used before its initialization).
Therefore I need to inizialize it outside the foreach. If I use:
var tempResult = products;
Inside my foreach
I just sum up to the whole set my desidered resultSet.
Therefore the only two possible solutions are:
1) Create a method in the Repository that returns an empty IQueryable<Product>
(factory pattern)
2) Use reflection (if feasible, not sure yet)
I found both solutions a bit "dirty". Is there any other approach/pattern to achieve this? Thanks