Search code examples
c#dictionarycastingkeyvaluepair

How to cast dictionaries stored in the session in C#?


Placing in session:

HttpContext.Current.Session.Add("_ProjectRights", ProjectRepository.GetProjectRechten(user1.UserId).ToList());

query:

var data= Db.Users.SingleOrDefault(s => s.UserPk == userId)?.ProjectUser
 .Select(se => new { Key = se.primaryKey1.ToString(), 
Items = string.Join(",", se.ProjectRight.Select(sel => sel.primaryKey2).ToList()) });

IDictionary<string, string> dictionary = data.ToDictionary(pair => pair.Key, pair => pair.Items);

Failed cast:

var privilegeLevelsDict = (Dictionary<string, List<string>>)HttpContext.Current.Session["_ProjectRechten"];

Succesful cast:

var privilegeLevelsDict = (List<KeyValuePair<string, List<string>>>)HttpContext.Current.Session["_ProjectRechten"];

Why does the first cast not work? Why do I have to cast to a List of KeyValuePairs instead of a dictionary, even though I first placed a dictionary in the session variable?


Solution

  • You're adding a list to the session, here:

    HttpContext.Current.Session.Add(
        "_ProjectRights", 
        ProjectRepository.GetProjectRechten(user1.UserId).ToList())
    

    Note the ToList() call. If GetProjectRechten is returning a dictionary and that's what you want to be in the session (and if it can be serialized) then you could just remove the ToList() call.

    HttpContext.Current.Session.Add(
        "_ProjectRights",
        ProjectRepository.GetProjectRechten(user1.UserId))
    

    If you can't serialize a dictionary but want to recreate it later, you can do that easily:

    var storedValue = HttpContext.Current.Session["_ProjectRechten"];
    var list = (List<KeyValuePair<string, List<string>>>) storedValue;
    var dictionary = list.ToDictionary(pair => pair.Key, pair => pair.Value);