Darren Lau
Darren Lau

Reputation: 2055

Fastest way to assign item from a list to another item in a list

I've two class which is product and order, please look at the class attribute blow

public class Product()
{ 
  public int ProductId { get;set; }
  public string ProductName { get;set; }
  public List<Order> OrderList { get;set; }
}

public class Order()
{
  public int OrderId { get;set; }
  public int ProductId { get;set; }
  public string OrderNumber { get;set; }
  public string OrderDescription { get;set; }
}

and i have a separate call to get the data from each of the class

var productList = ProductService.GetAllProductList();
var orderList = OrderService.GetAllOrderList();

What i'm trying to achieve here is that i want to assign order list object to product, i can achieve this by doing like below

  foreach(var product in productList)
  {
     var selectedOrderList = orderList.Where(x => x.ProductId = product.ProductId).ToList();
     product.OrderList = selectedOrderList;
  }

Imaging if my product and order has large amount of data, it could caused some performance issue.

It's because we are doing unnecessary lookup in orderList as some of the order data is already assigned.

Is there any better way to achieve this ?

Upvotes: 1

Views: 354

Answers (2)

Ivan Stoev
Ivan Stoev

Reputation: 205779

It's because we are doing unnecessary lookup in orderList

I would not call it unnecessary, but for sure it is inefficient due to linear time complexity of the LINQ to Objects Where method, leading to O(N * M) complexity of the processing algorithm.

So you need a fast alternative, and the easiest standard (and quite efficient hash based implementation) is to build and use Orders lookup by ProductId using ToLookup method, which will trim the time complexity to O(N + M):

var ordersByProductId = orderList.ToLookup(order => order.ProductId);
foreach (var product in productList)
     product.OrderList = ordersByProductId[product.ProductId].ToList();

Upvotes: 3

user452596
user452596

Reputation:

If you are already returning a list of all orders from the service in orderList... then doing a linq WHERE from a list in memory shouldn't have any performance issues.

Or you change the service to populate product.OrderList before returning it.

Upvotes: 0

Related Questions