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();

      

+1


a source to share


2 answers


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.

+6


a source


I like to be explicit with Linq and lambdas queries. I suggest defining your function as List <Product> (or IEnumerable <Product>) and then adding .ToList () to the where clause. I'm assuming the Products type is some sort of collection?



0


a source







All Articles