Availability:
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:
var groupedCustomers = orders.GroupBy(i => i.CustomerId) .Select(i => new { CUSTOMER = i.Key, ORDERS = i.Select(j => j.ProductId) .OrderBy(j => j)
And here is the comparator.
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 the smart GetHashCode function, you can try something like this:
public int GetHashCode(int[] obj) { return string.Join(",", obj.Select(i => i.ToString())).GetHashCode(); }
source share