c# - 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?
解决方案
你想做的叫做投影,你想投影每个项目并将它们变成其他东西。
所以你可以使用Select
:
var pdl = pds.Select(p => new Product
{
desc = p.Description,
prodId = Convert.ToInt16(p.pId)
}).ToList();
推荐阅读
- json - JSON 分页(每页 20 个数据)
- c# - 如何将 MSSQL_CERTIFICATE_STORE 从一台机器移动到另一台机器?
- android - 即使结果不为空,setObservers 也会立即进入 NetworkStatus.ERROR
- pine-script - Pinescript v1 到 v4 的转换
- postgresql - postgresql while/循环函数
- python - 针对 USACO 问题的 Python 代码中的 EOF 错误重新植被
- git - 如何从最新提交创建分支
- python - 如果所有值都相同,Pandas 不会在 groupby 和 nlargest 之后创建额外的(重复的)索引
- swiftui - SwiftUI:环境中的商店关闭?
- javascript - Electron:如何将消息/数据从预加载传递到渲染器?