0

I've been working on this code for a while now, and am very slow at this point. I don't know if the answer is obvious, but I haven't been able to think of a way to convert this bit:

foreach (Item i in stockList)
{
    if (i == order.OrderItem)
        i.ChangeStock(order.NumberOfItems);
}
outStandingOrders.Remove(order);

into a lambda expression. The best I could come up with is

stockList.ForEach(i => i == order.OrderItem)

(Don't know where to go from here)

There is also only ever one item in stockList that is equal to order.OrderItem.

Any help would be hot

Thanks!

4
  • Why do you want to convert it to lambda? Commented Apr 30, 2014 at 7:59
  • It should be cleaner and I don't know how, so that makes me curious. Based off of the documentation it should be possible. Commented Apr 30, 2014 at 8:00
  • 1
    Why should it be cleaner? The code looks pretty good to me. Commented Apr 30, 2014 at 8:01
  • I thought it would be cleaner, I guess that's not the case. Normally it cleans up fairly well. I'm also trying to become more familiar with lambdas. Commented Apr 30, 2014 at 8:05

2 Answers 2

4

Basing on your information that "There is also only ever one item in stockList that is equal to order.OrderItem", I would write it simply:

 var item = stockList.FirstOrDefault(i => i == order.OrderItem);
 if (item != null)
 {
     item.ChangeStock(order.NumberOfItems);    
 }
Sign up to request clarification or add additional context in comments.

6 Comments

and what if there are multiple orderitems in stocklist? This would work only for first
There aren't multiple Orders in stockList.
oh, missed that line ^^
If there's only ever excatly one matching item, I would use Single (or SingleOrDefault if there can be zero matching items). This would make the intent clearer and throw an expection if there are more than a single matching item. If it's wrong if there are more than one matching item, you want to know it as early as possible.
I missed that line, too :-D
|
4
stockList.FindAll(i => i == order.OrderItem)
.ForEach(i => i.ChangeStock(order.NumberOfItems));

Untested, just typed ^^

2 Comments

Works like a charm, although it needed one more parenthesis at the end.
Added the missing parenthesis

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.