Is there a one line LINQ statement that would replace the foreach loop in the code below?
public static ReplaceItemsOnOrder(Order order, List<OrderItem> replacements)
{
order.Items.Clear();
foreach (var item in replacements)
{
order.Items.Add(item);
}
}
EDIT:
Here is a simplified definition for the Order class:
public class Order
{
private Collection<OrderItem> _items = new Collection<OrderItem>();
public Collection<OrderItem> Items
{
get { return _items; }
}
}
You could write the following:
order.Items.Clear();
replacements.ForEach(order.Items.Add);
Alternatively if there's an addRange method (available on List<T>):
order.Items.Clear();
order.Items.AddRange(replacements);
It's not LINQ but there's AddRange
order.Items.AddRange(replacements);
But you haven't said what Items is, so unless it's a List that method won't be available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With