Faizan Mubasher
Faizan Mubasher

Reputation: 4569

Adding Event in Lambda Expressions

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!

Upvotes: 0

Views: 109

Answers (1)

Raja Nadar
Raja Nadar

Reputation: 9489

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.

Upvotes: 1

Related Questions