Friday, January 28, 2011

.NET shopping cart (c#) with lambda expressions

In this article I am going to explain how to create a simple shopping cart with lambda expressions and generic list.
To archive this I am going to create two classes called Product and Basket.
Product class supposes to store all the product information and basket class suppose to store list of the products.
The following figure shows my product class




Then I am going to create next class, class Basket. In this class I got three properties





Getters and setters are look like follows








For the totalAmount I eliminated setter and for the get the total amount I used lambda expression






I am going to retrieve item count as follows

Apart from that I have a method to remove products from the basket and I am using lambda expressions for that as well.


You can download Product class from here and Basket class from here.

Now let’s see how to use these two classes in the real world.

  1. create an instance of basket class
  2. create an instance of Product class and add product details
  3. Add product instance to basket instance.
  4. Add basket instance to session variable for future use.

This code will work fine for the first time. But the second time when user clicks on the AddToBasket button it will create new instance. To avoid such a situation you should always check whether the basket is created or not. If created you can add second product to the existing basket, if not you have to create a new basket as above. Complete code snippet will look like follows