//I need to deifne productQuery here
if (test == true)
{
var productQuery = ordersRepository.ProductIn; //it returns IQueryable<ProductIn> type
}
else
{
var productQuery = ordersRepository.ProductOut; //it returns IQueryable<ProductOut> type
}
How can I define the productQuery variable?
Thank you!
[EDIT]
dynamic productType;
if (test == true)
{
productType = ordersRepository.ProductIn; //it returns IQueryable<ProductIn> type
}
else
{
productType = ordersRepository.ProductOut; //it returns IQueryable<ProductOut> type
}
var productQuery = productType as IQueryable<ProductIn>;
if (productQuery == null)
{
productQuery = productType as IQueryable<ProductIn>;
}
I do this way, is it right way?
You could declare it as a dynamic type, if you’re ok with deferring type resolution until runtime.
Your other choice is to declare it as an object type, and then cast it back to the other type as needed.
Update after op’s edit
Let’s say you have a dynamic type productQuery. To use Linq on it, you need to define the types of the delegate. Let’s say that types ProductIn and ProductOut each have a string-type property ProductNo. Then you could write your query like this, again making use of dynamic.
However … I think you could make your life a lot easier by changing your whole approach. You’re clearly working against a common interface for ProductIn and ProductOut, so why not define that explicitly?
Now your code becomes a lot simpler. Write it like this: