开发者

storing dictionary in session

How do you create a dictionary of objects in the session? More specifically, I have a list of objects: MyList stores MyObject as the result of a linq query with the date as a parameter.

List<MyObject> Mylist;
MyList = GetObjects(TheDate);

Now I'd like to store MyList in the sessi开发者_如何学JAVAon object in a dictionary with the date as the key. When the page needs a MyList for a specific date, first search the dictionary and if it's blank for that date, get the data from the GetObjects query and store the result in the dictionary in the session.

What's the best way to do this?

Thanks.


Sample for storing a dictionary in session:

List<MyObject> Mylist;
MyList = GetObjects(TheDate);
Dictionary<DateTime> myDictionary = new Dictionary<DateTime>();
myDictionary[TheDate] = MyList;
Session["DateCollections"] = myDictionary;

Sample for retrieving from session (should have null check to be sure it's there):

Dictionary<DateTime> myDictionary  = (Dictionary<DateTime>) Session["DateCollections"];


I would create some sort of facade around accessing Session variables, which makes retrieving and setting values very easy. Plus you don't have to worry about getting session var names correct as they are all stored in the same place. Example:

public static class SessionVars
{
     public static Dictionary<DateTime> DateCollections
     {
        get { return (Dictionary<DateTime>)HttpContext.Current.Session["DateCollections"]; }
        set { HttpContext.Current.Session["DateCollections"] = value; }
     }
}

Then accessing it anywhere in your code would look like this:

  var List<MyObject> mylist = SessionVars.DateCollections[TheDate];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜