首页 > 解决方案 > 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?

标签: c#.netlambda

解决方案


你想做的叫做投影,你想投影每个项目并将它们变成其他东西。

所以你可以使用Select

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

推荐阅读