Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Contains() on a list of custom class objects

I'm trying to use the .Contains() function on a list of custom objects

This is the list:

List<CartProduct> CartProducts = new List<CartProduct>(); 

And the CartProduct:

public class CartProduct {     public Int32 ID;     public String Name;     public Int32 Number;     public Decimal CurrentPrice;     /// <summary>     ///      /// </summary>     /// <param name="ID">The ID of the product</param>     /// <param name="Name">The name of the product</param>     /// <param name="Number">The total number of that product</param>     /// <param name="CurrentPrice">The currentprice for the product (1 piece)</param>     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;     } } 

So i try to find a similar cartproduct within the list:

if (CartProducts.Contains(p)) 

But it ignores similar cartproducts and i don't seem to know what it checks on - the ID? or it all?

Thanks in advance! :)

like image 337
Jan Johansen Avatar asked Apr 13 '10 11:04

Jan Johansen


People also ask

How to access list of objects in C#?

The code is: struct m1 { public int a; public int b; } int main() { List <m1> mList; m1. initialize; //new. and add some items to it.

Can we have list of objects?

Yes, it is absolutely fine to have an object contains list of object.

How to create a generic list in C#?

How to Add Elements into a Generic List<T> Collection in C#? If you want to add elements to the generic list collection then you need to use the following Add() and AddRange() method of the Generic List Collection Class in C#. Add(T item): The Add(T item) method is used to add an element to the end of the Generic List.


1 Answers

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.

like image 134
Paul Turner Avatar answered Sep 28 '22 08:09

Paul Turner