Let's say I have a dictionary that I want to store in the session. This dictionary will be storing a list of object with a date as the key.
Dictionary<DateTime, List<MyObjects>> SessionDictio开发者_JAVA技巧naryMyObjects = new...
How do I put a list MyList in the dictionary with the key 31/1/2011 and how do I retrieve the list for 1/19/2011 from the dictionary?
Thanks.
Like this?
Dictionary<DateTime, List<MyObjects>> SessionDictionaryMyObjects = Session["SessionDictionaryMyObjects"] as Dictionary<DateTime, List<MyObjects>>;
if (SessionDictionaryMyObjects == null)
{
Session["SessionDictionaryMyObjects"] = SessionDictionaryMyObjects =
new Dictionary<DateTime, List<MyObjects>>();
}
// Set value
SessionDictionaryMyObjects.Add(new DateTime(2011, 1, 31), yourListObject);
if (SessionDictionaryMyObjects.Contains(new DateTime(2011, 1, 19)))
{
// Get value
List<MyObjects> o = SessionDictionaryMyObjects[new DateTime(2011, 1, 19)];
}
You also should sheck if the value exists in the dictionary with ContainsKey
method
//to add
List<MyObjects> myList = new List<MyObjects>();
//myList.add("etc") ...
SessionDictionaryMyObjects.Add(DateTime.Parse("31/1/2011"),myList);
//to retrieve
if (SessionDictionaryMyObjects.ContainsKey(DateTime.Parse("1/19/2011")))
{
List<MyObjects> myList= SessionDictionaryMyObjects[DateTime.Parse("1/19/2011")];
}
精彩评论