0

I have the following code here is how I add a list of values to session

public ActionResult Add(Product product)
{
 if (Session["AddToCart"] == null)
  {
    Session["AddToCart"] = new List<Product>();
  }
  var list = (List<Product>)Session["AddToCart"];
  list.Add(product);  
}     

but how to remove a single record when a session contains multiple records. I am trying to pass an Id but it is not removing the record from the session. Here is how I perform the next step.

Public ActionResult Remove(Product product)
{
 Product prod=db.Products.Single(x=>x.Id==product.Id);
 var list=(List<Product>)Session["AddToCart"];
 //Is this the correct approach
 list.Remove(prod);
 }

The above code doesn't works. Am I correct or is there anything missing plz correct the above code. Thanks.

Zaker
  • 537
  • 16
  • 30
  • possible duplicate of [Using LINQ to remove elements from a List](http://stackoverflow.com/questions/853526/using-linq-to-remove-elements-from-a-listt) – Travis J Jan 26 '15 at 07:02

1 Answers1

1

Try this,

var list=(List<Product>)Session["AddToCart"];
list.RemoveAll(p => p.Id == product.Id);

Your choice of finding the product with the code db.Products.Single(x=>x.Id==product.Id); may not be the same object with the one in the session.

Edit:

Or you can implement IEquatable<Product> interface. In this case your code would work too.

public class Product : IEquatable<Product>
{
    public int Id;

    public bool Equals(Product prod)
    {
        return prod.Id == Id;
    }

    // Rest of the class
}
serdar
  • 1,564
  • 1
  • 20
  • 30
  • +1 and thanks for your answer I got it. And when to use Remove(object) and as per your statement My choice of finding............may not be the same means what could you plz explain that.Thanks again – Zaker Jan 26 '15 at 07:38
  • @User You can use Remove(object) if you know that the object is in the collection. In your case you find the object(to be deleted) from another collection. `Id` fields being the same does not mean that the objects are same. You can easily create 2 `Product` objects with same `Id`. These objects are different objects. In general: If you create a reference type twice(and even make all the fields same) these objects are different objects(each allocating different area in memory). And classes are reference types. – serdar Jan 26 '15 at 07:59
  • @User For another solution I have made an edit in the answer. – serdar Jan 26 '15 at 08:22