user3587180 user3587180 - 2 months ago 8
C# Question

How to avoid writing three loops in this example?

In the below code example, how can I avoid writing 3 loops. I'm not sure how to keep the code readable and still optimize it. This is not the exact function I'm working on, but for brevity I updated it so it's for you guys to read.

int OrderQuantity = 5;
List<LineItem> Items = GetLineItems();
List<int> UniqueOrderIDs = new List<int>();

foreach (LineItem i in Items) {
if (UniqueOrderIDs.Contains(i.OrderID) == false) {
PurchaseOrder Order = GetOrder(i.OrderId);
Order.ModifiedDate = Now;
UpdateOrder(Order);
UniqueOrderIDs.Add(i.OrderID);
}
}

foreach (int id in UniqueOrderIDs) {
decimal TaxableAmount = 0;

foreach (LineItem i in Items) {
If(i.OrderID == id){
i.OrderQuantity = OrderQuantity;
UpdateItem(i)

TaxableAmount += i.Cost;
}
}

UpdateTaxAmount(id, TaxableAmount);
}

Answer

You can do, something like (I omit bounds checking here)

List<LineItem> items = GetLineItems(OrderID);
var sorted = items.OrderBy(i=>i.OrderID);

int id = sorted.First().OrderID; //get 1st element's id

foreach (LineItem i in sorted.Skip(1)) //skip 1st one
{
    if(i.OrderID == id)
    {
        i.OrderQuantity = OrderQuantity;
        UpdateItem(i)    
        TaxableAmount += i.Cost;            
    }
    else 
       id = i.OrderID;
}

....

You sort LineItem list by OrderID, after simply iterate over it, and while it is the same, do whatever you need to do.

There will be someone that, probably, would opt for LINQ solution, but to my taste, this looks much simpler and clear then LINQ solution might be in this situation.