How to group object in C# by its equality using Linq

2135 views c#
3

Scenario:

I have a list of the object 'Order and would like to group by the identical's List<OrderLine> property, by identical I mean same quantity of lines as well as same Sku/Quantity values in the same order' and return the list of order values grouped:

class Order
{
    public int OrderNumber { get; set; }
    public List<OrderLine> Lines { get; set; }
}

class OrderLine
{    
    public string Sku { get; set; }
    public int Quantity { get; set; }       
}

Input sample:

+-------------+-----+----------+
| OrderNumber | Sku | Quantity |
+-------------+-----+----------+
|           1 | A   |       10 |
|           1 | B   |       20 |
|           2 | A   |       10 |
|           3 | A   |       10 |
|           3 | B   |       20 |
+-------------+-----+----------+

Output desired:

Lines = Lines.Count(); the count of lines for each grouped identical

Pieces = SUM(OrderLine.Quantity); the sum of all quantities for each grouped identical orders.

+-----------------+-------+--------+
| TotalIdenticals | Lines | Pieces |
+-----------------+-------+--------+
|               1 |     1 |     10 |
|               2 |     2 |     30 |
+-----------------+-------+--------+

I used a table representation to make it clearer. So as above there is only 1 record with 1 line (order 2) and qty 10. on the other hand, there are two orders with the same list of lines (order 1 and 3)

So I need that after running a linq algorithm, it would generate for me a object kind of

> "identical 1".Orders -> [2]
> "identical 2".Order -> [1,3]

What I tried to do?

var identicals = orderList.GroupBy(x => x.Lines)
                 .Where(g => g.Count() > 1)
                 .Select(g => g.Key)
                 .ToList();

The code above did not work, basicaly I just need to be able to group the Lines property (so its equality to other OrderLines), then I will be able to generate my output of lines/pieces... the only issue now is to be able to group my object order list by Lines list object similarity.

I hope I was clear in my question, if you need more details please let me know and I will add here.

answered question

1 Answer

12

To be able to group by Lines you need to implement IEqualityComparer<List<OrderLine>> and pass it into GroupBy method: var groups = orders.GroupBy(o => o.Lines, o => o, new OrderLineEqualityComparer());

internal class OrderLineEqualityComparer : IEqualityComparer<List<OrderLine>>
{
    public bool Equals(List<OrderLine> x, List<OrderLine> y)
    {
        throw new NotImplementedException();
    }

    public int GetHashCode(List<OrderLine> obj)
    {
        throw new NotImplementedException();
    }
}

posted this

Have an answer?

JD

Please login first before posting an answer.