通过对重复信息进行分组从列表中创建对象

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 by,然后Customer使用子查询将分组结果映射到您的模型中:

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()
            });


以上是通过对重复信息进行分组从列表中创建对象的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>