Home > OS >  How to optimize the nested for loop with different lengths?
How to optimize the nested for loop with different lengths?

Time:09-17

I'm need to optimize 2 nested for loops using LINQ or Zip in c#, Because this code taking some time to load.

These two lists are loaded with api calls

List<OrderIncidentsDto> orderDtos = new List<OrderIncidentsDto>();
List<OrderItemDto> orderItemDtos = new List<OrderItemDto>();

I am trying iterate this data using two nested for loops

for (int incidents = 0; incidents < orderDtos.Count; incidents  ) 
{
        var oItems = new List<OrderItemDto>();
    for (int items = 0; items < orderItemDtos.Count; items  )
    {
        if (orderItemDtos[items].IncidentNumber == orderDtos[incidents].OrderIncidentName)
        {
            oItems.Add(orderItemDtos[items]);
            orderDtos[incidents].OrderItems = oItems;
        }
    }
}

Please suggest me the best way to reduce the lines of code or get rid multiple loops.

CodePudding user response:

Your current code has a time complexity of O(n^2) this can be reduced to O(n) by first indexing orderItemDtos by IncidentNumber and then just looping over the orderDtos picking out their order items

var orderItemLookup = orderItemDtos.ToLookup(x => x.IncidentNumber);
orderDtos.ForEach(order => order.OrderItems = orderItemLookup[order.OrderIncidentName]);
  • Related