c# - 通过对重复信息进行分组从列表中创建对象
问题描述
考虑下面的Customer
课程 -
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public List<Product> Products { get; set; }
}
public class Product
{
public string Name { get; set; }
public int Price { get; set; }
}
如果我有一个List<Purchase>
,在哪里Purchase
-
public class Purchase
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public string ProductName { get; set; }
public int Price { get; set; }
}
并且该列表包含重复的客户相关信息,例如 -
var list = new List<Purchase>
{
new Purchase { CustomerId=1, CustomerName="Alice", ProductName="CPU", Price=250 },
new Purchase { CustomerId=1, CustomerName="Alice", ProductName="RAM", Price=100 },
new Purchase { CustomerId=1, CustomerName="Alice", ProductName="HDD", Price=150 },
new Purchase { CustomerId=2, CustomerName="Bob", ProductName="RAM", Price=100 },
new Purchase { CustomerId=2, CustomerName="Bob", ProductName="SSD", Price=200 },
};
如何Customer
从此列表中创建对象列表?
解决方案
使用 LINQ,您可能希望使用group byCustomer
,然后使用子查询将分组的结果映射到您的模型中:
var customerList = from p in list
group p by new { p.CustomerId, p.CustomerName } into grp
select new Customer() {
Id = grp.Key.CustomerId,
Name = grp.Key.CustomerName,
Products = grp.Select(
prd => new Product() {
Name = prd.ProductName,
Price = prd.Price
}
).ToList()
};
或者,如果您愿意:
var customerList = list.GroupBy(p => new { p.CustomerId, p.CustomerName })
.Select(grp => new Customer() {
Id = grp.Key.CustomerId,
Name = grp.Key.CustomerName,
Products = grp.Select(
prd => new Product() {
Name = prd.ProductName,
Price = prd.Price
}
).ToList()
});
推荐阅读
- angular - ngrx - 从商店中为多个可观察对象选择多个项目
- python - 重构更长的“单行”if-condition-assignment(三元 If)的 Pythonic 方式
- node.js - 通过事件网格传递来自 Azure Function 的 HTTP 请求
- c++ - 带参数的累积正态分布函数的逆
- c# - 打印出现问题,然后删除文档
- regex - 不允许前导空格和 (^\\/:*?"<>|) 中的任何字符的正则表达式
- pentaho - 是否可以在 Pentaho 的 PDI 转换步骤中获得“Carte Object ID”?
- flutter - 如何在 Widget initState() 中获取 Navigator 的上下文?
- c# - Buy X Pay for Y 算法
- perl - 我正在尝试通过使用字符串 MNPPORTIN,00:11:16 和常规 exp 和 grep 函数从数组中获取匹配的元素