LINQ to 模型分组

LINQ to model grouping

我正在尝试根据数据库视图中的多个列对多个项目进行分组。我已经梳理了无数关于这个主题的帖子,但没有解决我的问题。

这是一个示例视图定义:

|客户 ID|订单 ID|产品|

这是一些示例数据:

CustomerID|OrderID|Product
    1     |  123  | Apple
    1     |  123  | Pear
    1     |  124  | Apple

这是我想在 json 中实现的目标:

CustomerID: 1
OrderIDs: [
  {OrderID: 123,
  Product: [
    Apple,
    Pear
  ]},
  {OrderID: 124,
  Product: [
    Apple
  ]}
]

这些是我的类

class CustomerOrders
{
    public int CustomerID { get; set; }
    public IEnumerable<OrderIDs> OrderID;
}

class OrderIDs
{
    public int OrderID { get; set; }
    public int Product { get; set; }
}

还有我的 Linq:

.Select(co => new CustomerOrders
{
 CustomerID = co.CustomerID
 OrderIDs = co.Select(o => new OrderID
 {
   OrderID = o.OrderID
   Product = o.Product
 }
}

但是这个returns以下json:

CustomerID: 1
OrderIDs: [
  {
  OrderID: 123,
  Product: [
    Apple,
    Pear
  ]},
  OrderID: 123,
  Product: [
    Apple,
    Pear
  ]},
  {OrderID: 124,
  Product: [
    Apple
  ]}
]

您的 类 已经存在一些问题,例如 Product 设置为 int 而它应该是 IEnumerable 。 问题是您没有在 Linq 中使用 GroupBy。

这是我的结果:

static void Main(string[] args)
{
    var data = new[]
    {
        new DbRow { CustomerId = 1, OrderId = 123, Product = "Apple" },
        new DbRow { CustomerId = 1, OrderId = 123, Product = "Pear" },
        new DbRow { CustomerId = 1, OrderId = 124, Product = "Apple" }
    };

    var resultFullLinq = data.GroupBy(row => row.CustomerId)
        .Select(groupCustomer => new CustomerOrder
        {
            Id = groupCustomer.Key,
            Orders = groupCustomer.GroupBy(row => row.OrderId)
                .Select(groupOrder => new Order
                {
                    Id = groupOrder.Key,
                    Products = groupOrder.Select(row => row.Product).ToList()
                }).OrderBy(order => order.Id).ToList()
        }).ToList();

    // OR use methods

    var resultMethods = data.GroupBy(row => row.CustomerId).Select(groupCustomer => CreateCustomerOrder(groupCustomer)).ToList();
}

private static CustomerOrder CreateCustomerOrder(IGrouping<int, DbRow> groupCustomer)
{
    return new CustomerOrder
    {
        Id = groupCustomer.Key,
        Orders = GetOrderIds(groupCustomer).OrderBy(order => order.Id).ToList()
    };
}

private static IEnumerable<Order> GetOrderIds(IGrouping<int, DbRow> groupCustomer)
{
    return groupCustomer.GroupBy(row => row.OrderId).Select(groupOrder => GetOrderId(groupOrder));
}

private static Order GetOrderId(IGrouping<int, DbRow> groupOrder)
{
    return new Order
    {
        Id = groupOrder.Key,
        Products = groupOrder.Select(p => p.Product)
    };
}

// Class that represent a row of the database
public class DbRow
{
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    public string Product { get; set; }
}

class CustomerOrder
{
    public int Id { get; set; }
    public IEnumerable<Order> Orders;
}

class Order
{
    public int Id { get; set; }
    public IEnumerable<string> Products { get; set; }
}