简体   繁体   English

Linq groupby有两个属性

[英]Linq groupby on two properties

Say I have a list of orders. 说我有一份订单清单。 Each order have a reference to the customer and the product they bought. 每个订单都有一个参考客户和他们购买的产品。 Like so: 像这样:

class Orders 
{
    public int CustomerId {get;set;}
    public int ProductId {get;set;}
}

I want to group all orders where different customers have the same set of products are in the same group. 我想将不同客户拥有同一组产品的所有订单分组在同一组中。

  • Customer 1 - Product 1&2 客户1 - 产品1和2
  • Customer 2 - Product 1&2&3 客户2 - 产品1和2&3
  • Customer 3 - Product 1&2 客户3 - 产品1和2
  • Customer 4 - Product 3&4&5 客户4 - 产品3和4&5

In this case, the orders for customer 1&3 will be in the same group, and orders for 2&4 will have their own group. 在这种情况下,客户1和3的订单将在同一组中,而2和4的订单将拥有自己的组。

Is this possible to achieve with LINQ? LINQ可以实现这一点吗? I started with trying to group by the CustomerId , but am at a lost on how to proceed from there. 我开始试图通过CustomerId进行分组,但我却迷失了如何从那里开始。

Having: 有:

List<Orders> orders = new List<Orders>();

orders.Add(new Orders { CustomerId = 1, ProductId = 1 });
orders.Add(new Orders { CustomerId = 1, ProductId = 2 });
orders.Add(new Orders { CustomerId = 2, ProductId = 2 });
orders.Add(new Orders { CustomerId = 2, ProductId = 3 });
orders.Add(new Orders { CustomerId = 3, ProductId = 1 });
orders.Add(new Orders { CustomerId = 3, ProductId = 2 });
orders.Add(new Orders { CustomerId = 4, ProductId = 3 });
orders.Add(new Orders { CustomerId = 4, ProductId = 4 });

LINQ Query: LINQ查询:

 var groupedCustomers = 
         orders.GroupBy(i => i.CustomerId)
               .Select(i => new { CUSTOMER = i.Key, 
                                  ORDERS = i.Select(j => j.ProductId)
                                            .OrderBy(j => j)
                                          //.Distinct() to ignore duplicate orders
                                            .ToArray() })
               .ToList();

 var result = groupedCustomers.GroupBy(i => i.ORDERS, new IntArrayComparer()).ToList();

And here is the comparer. 这是比较器。

 public class IntArrayComparer : IEqualityComparer<int[]>
 {    
     public bool Equals(int[] x, int[] y)
     {
         return x.SequenceEqual(y);
     }

     public int GetHashCode(int[] obj)
     {
         return base.GetHashCode();
     }
 }

EDIT: If you are looking for smarter GetHashCode function, you may try something like this: 编辑:如果您正在寻找更智能的GetHashCode函数,您可以尝试这样的事情:

public int GetHashCode(int[] obj)
{
    return string.Join(",", obj.Select(i => i.ToString())).GetHashCode();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM