I\'m trying to use the .Contains()
function on a list of custom objects
This is the list:
List CartProducts = new Lis
By default reference types have reference equality (i.e. two instances are only equal if they are the same object).
You need to override Object.Equals
(and Object.GetHashCode
to match) to implement your own equality. (And it is then good practice to implement an equality, ==
, operator.)
Implement override Equals()
and GetHashCode()
public class CartProduct
{
public Int32 ID;
...
public CartProduct(Int32 ID, ...)
{
this.ID = ID;
...
}
public override int GetHashCode()
{
return ID;
}
public override bool Equals(Object obj)
{
if (obj == null || !(obj is CartProduct))
return false;
else
return GetHashCode() == ((CartProduct)obj).GetHashCode();
}
}
used:
if (CartProducts.Contains(p))
You need to implement IEquatable
or override Equals()
and GetHashCode()
For example:
public class CartProduct : IEquatable<CartProduct>
{
public Int32 ID;
public String Name;
public Int32 Number;
public Decimal CurrentPrice;
public CartProduct(Int32 ID, String Name, Int32 Number, Decimal CurrentPrice)
{
this.ID = ID;
this.Name = Name;
this.Number = Number;
this.CurrentPrice = CurrentPrice;
}
public String ToString()
{
return Name;
}
public bool Equals( CartProduct other )
{
// Would still want to check for null etc. first.
return this.ID == other.ID &&
this.Name == other.Name &&
this.Number == other.Number &&
this.CurrentPrice == other.CurrentPrice;
}
}
You need to create a object from your list like:
List<CartProduct> lst = new List<CartProduct>();
CartProduct obj = lst.Find(x => (x.Name == "product name"));
That object get the looked value searching by their properties: x.name
Then you can use List methods like Contains or Remove
if (lst.Contains(obj))
{
lst.Remove(obj);
}
If you want to have control over this you need to implement the [IEquatable interface][1]
[1]: http://This method determines equality by using the default equality comparer, as defined by the object's implementation of the IEquatable.Equals method for T (the type of values in the list).
If you are using .NET 3.5 or newer you can use LINQ extension methods to achieve a "contains" check with the Any extension method:
if(CartProducts.Any(prod => prod.ID == p.ID))
This will check for the existence of a product within CartProducts
which has an ID matching the ID of p
. You can put any boolean expression after the =>
to perform the check on.
This also has the benefit of working for LINQ-to-SQL queries as well as in-memory queries, where Contains
doesn't.