Xami Yen
Xami Yen

Reputation: 267

Select Multiple Values from a Collection using Lambda Expression

How do I select two or more values from a collection into a list using a single lambda expression? Here is what I am trying:

List<Prodcut> pds=GetProducts();
List<Product> pdl = new List<Product>();
foreach (Product item in pds)
{
    pdl.Add(new Product
    {
        desc = item.Description,
        prodId = Convert.ToInt16(item.pId)
    });
}

GetProducts() returns a list of Products that have many (about 21) attributes. The above code does the job but I am trying to create a subset of the product list by extracting just two product attributes (description and productId) using a single lambda expression. How do I accomplish this?

Upvotes: 1

Views: 1832

Answers (1)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

What you want to do is called projection, you want to project each item and turn them into something else.

So you can use a Select:

var pdl = pds.Select(p => new Product 
                              { 
                                  desc = p.Description, 
                                  prodId = Convert.ToInt16(p.pId)
                              }).ToList();

Upvotes: 4

Related Questions