C# – How To Define The Return Type In A Function With LINQ

asp.netcentity-frameworklinqlinq-to-sql

I would like to know how to define a returntype in a function in
following situation.

I've got a products and I was 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 its give me casting error. as you can see what i want to achieve is based on my parameter its give me a result set. some time bunch of products & some time single product. i m new to linq so any help would be appreciated.

The error is Unable to cast object of type 'System.Data.Objects.ObjectQuery`1[TTDCore.Theatres]' to type 'TTDCore.Theatres'

when i m binding it to gridview. here is a code

Products p = Class1.GetProducts(0);

GridView1.DataSource = p;
GridView1.DataBind();

Best Answer

You want to return IEnumerable<Product>, which represents an iterable (or enumerable) of objects of type Product. LINQ in general is all based around this generic type, so it's generally what you want to return as a result of a query.

I believe your code should 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 meant something else in your question. I wasn't totally sure what precisely you were searching for.