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!
-
Why do you want to convert it to lambda?Kamil T– Kamil T2014年04月30日 07:59:10 +00:00Commented 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.user3421751– user34217512014年04月30日 08:00:07 +00:00Commented Apr 30, 2014 at 8:00
-
1Why should it be cleaner? The code looks pretty good to me.Lasse V. Karlsen– Lasse V. Karlsen2014年04月30日 08:01:56 +00:00Commented 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.user3421751– user34217512014年04月30日 08:05:06 +00:00Commented Apr 30, 2014 at 8:05
2 Answers 2
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);
}
6 Comments
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.stockList.FindAll(i => i == order.OrderItem)
.ForEach(i => i.ChangeStock(order.NumberOfItems));
Untested, just typed ^^