Search code examples
c#session-variables

Can I make a Session variable that behaves like a vector/list?


So, I'm using C# and I really need to store in a Session variable multiple data. I can't define as many Session variables as I need because I the number could be infinite.

I need to store everything in a Session, then loop through it. Is it possible?

So: I have a page with products, the Client can ADD to the basket as many items as he wants (all of this occurrs on the same page).


Solution

  • You can iterate over all keys or store a list of elements using one key "basket" (or "cart"):

    IList<CartItem> GetCartLines()
    {
        return Session["Basket"] as List<CartItem>;
    }
    
    void AddToCart(CartItem item)
    {
        var cartLines = Session["Basket"] as List<CartItem>;
        if(cartLines==null)
            Session["Basket"] = cartLines = new List<CartItem>();
        cartLines.Add(item);
    }