1

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?

1 Answer 1

4

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Simple and perfect!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.