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 session 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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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"];

Method 2

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];


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x