如何将数据分组并按组存储在新列表中

本文关键字:新列表 列表 数据 存储 | 更新日期: 2023-09-27 18:27:47

如何按组将数据存储在列表中?

比如

public class ProductPrice
{
  public string Name { get; set }
  public decimal Price { get; set; }
  // Date and other properties
}

然后有这样的记录:

+--------+--------+
| Name   | Price  |
+--------+--------+
| Chair  | 11     |
| Table  | 15     |
| Table  | 30     |
| Window | 24     |
| Chair  | 29     |
+--------+--------+

为了实现这样的列表应该做什么:

{
  {
    new ProductPrice { Name = "Chair", Price = 11 },
    new ProductPrice { Name = "Chair", Price = 29 },
  },
  {
    new ProductPrice { Name = "Table", Price = 15 },
    new ProductPrice { Name = "Table", Price = 30 }
  },
  {
    new ProductPrice { Name = "Window", Price = 24 }
  }
}

如您所见,它们按Name分组,并按组存储在列表中。如果能给他们提供一张折线图,看看他们的价格趋势,那就太好了。只是我很难创建列表。

简而言之,我可以创建一个按产品名称分组的List吗?此外,产品也可以有新的记录?

如何将数据分组并按组存储在新列表中

您需要的是一个List<List<ProductPrice>>,您可以执行:

List<List<ProductPrice>> groupedList = list.GroupBy(r => r.Name)
                    .Select(grp => new
                            {
                                List = grp.Select(r => r).ToList()
                            })
                    .Select(r => r.List)
                    .ToList();

这将在List中为您返回三个值,每组一个。

您还可以将结果投影到Dictionary<string, List<ProductPrice>>,其中key将是Product的名称,值将包含与Key相关的List<ProductPrice>。使用Enumerable.ToDictionary,如:

Dictionary<string, List<ProductPrice>> groupedList = list.GroupBy(r => r.Name)
                        .ToDictionary(grp => grp.Key, grp => grp.ToList());