.Contains() on a list of custom class objects

前端 未结 7 2173
天命终不由人
天命终不由人 2020-11-27 02:38

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

This is the list:

List CartProducts = new Lis         


        
7条回答
  •  醉梦人生
    2020-11-27 03:27

    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.

提交回复
热议问题