Dave
Dave

Reputation: 5029

Where clause on field outside Lambda expression class in Linq

If I were to use the following code to select products into a Class names Products, how would I be able to add a Where clause enabled=true without adding it to the class Products?

        List<Products> lp = db.products.Select(product => new Products
        {
            Name = product.name,
            Description = product.description,
            Category = product.Category
        }).ToList();

Adding .Where(x => x.enabled==true) doesn't work because enabled is not part of the Products class, just part of the products table.

Upvotes: 1

Views: 288

Answers (5)

Vicky
Vicky

Reputation: 829

var filter1 = Enumerable.Range(0, 50).Where(c => c % 2 == 0).Select(c => c).ToList();

Console.WriteLine(filter1[3]);

filter1.Insert(4, 13);

foreach (var v in filter1)
{
  Console.WriteLine(v);
}

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460108

I assume that you have tried to filter the products-list instead of the table. So you jst have to prepend the Where. This has also the advantage that you filter in the database instead of in the memory.

List<Products> lp = db.products
.Where(p => p.enabled)
.Select(product => new Products
{
    Name = product.name,
    Description = product.description,
    Category = product.Category
}).ToList();

Side-note: you should follow .NET naming conventions. For example use pascal case properties or class names. A class should normally be singular, if you want multiple of it's type use a List<Product>.

Upvotes: 4

David S.
David S.

Reputation: 6105

    List<Products> lp = db.products
        .Where(p => p.enabled)
        .Select(product => new Products
        {
            Name = product.name,
            Description = product.description,
            Category = product.Category
        }).ToList();

Also a good practice advice, I'd name the class in singular form, Product.

Upvotes: 4

NominSim
NominSim

Reputation: 8511

List<Products> lp = db.products.Where(product => product.enabled).
    Select(product => new Products
    {
        Name = product.name,
        Description = product.description,
        Category = product.Category
    }).ToList();

Upvotes: 1

RoadieRich
RoadieRich

Reputation: 6566

List<Products> lp = db.products
    .Where(x => x.enabled==true)
    .Select(product => new Products
    {
        Name = product.name,
        Description = product.description,
        Category = product.Category
    }).ToList();

Upvotes: 2

Related Questions