I have written the following linq statement but I can’t help feeling it could be simplified somehow. The purpose is to take a List<IEnumberable<Counterparty>> (counterpartyStatic in the query) objects and find the Orders that have a ClientId equal to Counterparty.CounterpartyId. Those order should then have the field ClientDesc updated to match the Counterparty.DescriptionField. Once this is done I need to raise an event passing all the orders that have been updated.
The OrderCache is a dictionary in case that is not obvious.
Here is the existing code:
var updates = new List<Order>();
lock (CacheLock)
{
counterpartyStatic.ToList().ForEach(cachedList =>
cachedList.ToList().ForEach(
counterparty =>
{
var orders = OrderCache.Where(kvp => kvp.Value.Client == counterparty.CounterpartyId);
orders.ToList().ForEach(kvp =>
{
kvp.Value.ClientDesc = counterparty.Description;
updates.Add(kvp.Value);
});
}));
}
RaiseEvent(updates);
Thanks for any help
Given that your “query” is really intended to cause side effects (ie: you’re changing the value’s ClientDesc in a deep nested loop), I would suggest writing this using loops instead of trying to use LINQ. This has a couple of advantages – you’re not making lists just to use
List<T>.ForEach, and the intention is far more clear:This is just as short as your original, but far more clear in terms of what is happening.
For an argument on why avoiding
List<T>.ForEachcan be beneficial, see Eric Lippert’s “foreach” vs “ForEach”.List<T>.ForEachhas even been removed for the new Windows Store apps, given the issues surrounding it.