Turn ListA of objects into ListA of lists that contain these objects by attribute value

Viewed 40

Let's say I have the following orders from the database, all in a list. All these orders map to 1 user.

Order1 ----- Confirmed  ---- 09/01/2022
Order1 ----- Dispatched ---- 10/01/2022
Order1 ----- Delivered  ---- 11/01/2022
Order2 ----- Confirmed  ---- 10/01/2022
Order2 ----- Dispatched ---- 11/01/2022

I receive these on .net c# to send them to the front end. Each order is an object like the following:

new {OrderID,Status,StatusDate}

And the list looks something like this:

[{},{},{},{},{}]

With each "{}" being one of the records above. I want to turn that list of order progress records into a list of lists, where each list contains the progress records of 1 order. So the list will look like this:

[[Order1 progress],[Order2 progress]]

Each order progress list will contain the exact records written above but only the records that have the same OrderID. Then I want to loop through that final list on my frontend to display on the user's page.

I have seen some solutions with Python(with a groupby import) but none that use C#.

2 Answers

Use LINQ's GroupBy method:

List<Order> listOfOrders = LoadOrders();

List<List<Order>> groupedListOfOrders = listOfOrders
    .GroupBy(o => o.OrderID, (_, orders) => orders.ToList());

you can use simple LINQ method and foreach loop.

List<Order> data = <your order data list>

output list of list

List<List<Order>> OrderList = new List<List<Order>>();

foreach (var order in data.Select(t => t.OrderId).Distinct())
 {
  OrderList.Add((List<Order>)data.Where(o => o.OrderId == order));
 }
Related