0

I have list of items and there is requirement that if an itemId is provided, it delete all items of that id from the list. Means, there can be multiple items in the list of same id.

private List<CartItem> items;
public void Remove(CartItem item)
{
    items.Remove(item);
    this.ItemRemoved(item); // This is call to an event whenever an item is removed from list.
}

As Remove function deletes one item from list and raises an event. I want to do it whenever multiple items are removed.

public void RemoveAll(int itemId)
{
    items.RemoveAll(item => item.ID == itemId); // Event here...
}

Here I want to add event so that whenever multiple items are removed, event can be raised for an individual item. How to add event code in Lambda expression?

Or is there any other way?

Compiler gives me an error when I try this:

items.RemoveAll(item => { this.ItemRemoved(item); item.ID == itemId; });

Error:

Not all code paths return a value in lambda expression of type 'System.Predicate<ShoppingCart.ShoppingCart.Items.CartItem>'

This is my event:

public event ItemRemoved ItemRemoved; // ItemRemoved is a delegate.

Thanks!

1 Answer 1

1

Try

items.RemoveAll(item => 
{
 if (item.ID == itemId) 
 { 
   // raise the event only for the items to be removed.
   this.ItemRemoved(item); 
   return true;
 }
 return false;
);

by default lambda expressions are single line return statements.

with multiple lines, we need to treat it as any anonymous delegate which means the code block needs to return a boolean, explicitly for the RemoveAll method.

Sign up to request clarification or add additional context in comments.

2 Comments

i think you should not raise the event for every item. only for the matching id ones..
O yes! I missed it. Thanks!

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.