views:

160

answers:

2

I need to build up a List<object> and cache the list and be able to append to it. I also need to be able to blow it away easily and recreate it. What is a simple way to accomplish this?

+1  A: 

This Tutorial is what I found to be helpful

Here is a sample

List<object> list = new List<Object>();

Cache["ObjectList"] = list;                 // add
list = ( List<object>) Cache["ObjectList"]; // retrieve
Cache.Remove("ObjectList");                 // remove
Asad Butt
+4  A: 

Something like this perhaps?

using System;
using System.Collections.Generic;
using System.Web;

public class MyListCache
{
    private List<object> _MyList = null;
    public List<object> MyList {
        get {
            if (_MyList == null) {
                _MyList = (HttpContext.Current.Cache["MyList"] as List<object>);
                if (_MyList == null) {
                    _MyList = new List<object>();
                    HttpContext.Current.Cache.Insert("MyList", _MyList);
                }
            }
            return _MyList;
        }
        set {
            HttpContext.Current.Cache.Insert("MyList", _MyList);
        }
    }

    public void ClearList() {
        HttpContext.Current.Cache.Remove("MyList");
    }
}

As for how to use.....

// Get an instance
var listCache = new MyListCache();

// Add something
listCache.MyList.Add(someObject);

// Enumerate
foreach(var o in listCache.MyList) {
  Console.WriteLine(o.ToString());
}  

// Blow it away
listCache.ClearList();
jessegavin
Well... serviceable. But I would make some changes. Primarily, I would always return a valid list. If it doesn't exist, create a new empty collection and cache it, rather than just returning whatever is in Cache["MyList"], which might be null.
Bryan
Yes Bryan, this example is quite simple. - But I took your suggestion to heart and updated my sample. Thanks.
jessegavin
In many/most real world scenarios you'll want to flush changes to some kind of persistant storage.
quillbreaker