How do I determine the return type in a function with LINQ?
I would like to know how to define the return type in a function in the following situation.
I have products and I am returning all information or one product at a time.
as you can see in my function defined below.
public static Products GetProducts(int pid)
{
var pro = from p in context.Products
select p;
if(pid > 0)
pro = pro.where(p => p.ProductID ==pid)
return (Products)p;
}
the problem is it is giving me casting error. as you can see what i want to achieve is based on my parameter it gives me a result set. some time a bunch of products and some time one product. I'm new to linq so any help would be appreciated.
Error Unable to pass object of type 'System.Data.Objects.ObjectQuery`1 [TTDCore.Theatres]' for input 'TTDCore.Theatres'
when i bind it to gridview. here is the code
Products p = Class1.GetProducts(0);
GridView1.DataSource = p;
GridView1.DataBind();
a source to share
You want to return IEnumerable<Product>
which is an iterable (or enumerable) object of type Product
. LINQ is generally based on this generic type, so it usually returns what you want to return as a result of a query.
I believe your code needs to be fixed to become something like this:
public static IEnumerable<Products> GetProducts(int pid)
{
var pro = from p in context.Products
select p;
if(pid > 0)
pro = pro.Where(p => p.ProductID == pid)
return pro;
}
Let me know if you mean anything else in your question. I was not completely sure what exactly you were looking for.
a source to share