How do I cast a ASP.NET session to get back my list?

11,577

Solution 1

You're much better off creating a class for the RefID value. This will allow you to do this:

public class RefContainer {
    // maybe RefID is not an int...?
    public Int32 RefID { get; set; }
}

Session["WorkingList"] = q.Select(x => new RefContainer { RefID = x.RefID });

var workingList = Session["WorkingList"] as IEnumerable<RefContainer>;
if (workingList != null) {
    var nextRecord = workingList
        .SkipWhile(i => i.RefID != currentRecord)
        .Skip(1).First();
}

Solution 2

Works for me:

Session["nnnn"] as List<double[]>;
Share:
11,577
Knox
Author by

Knox

Entrepreneur / CTO / VC in south Florida. Follow me on twitter @newtronic Or LinkedIn

Updated on June 14, 2022

Comments

  • Knox
    Knox almost 2 years

    Background: I have two web pages, one is a list of things, and the other is the detail of the thing. On the list, the user can filter and sort, which results in a sorted list. On the details, I would like the user to have Next and Previous navigation.

    I'm using ASP.Net Web Pages with Razor, edited with either WebMatrix or Visual Studio. The code on the list page is simple. The RefID is an integer Key uniquely identify the record:

    var db = Database.Open("dbname");
    ...
    var q = db.Query( sqlthatworks , passInVarables);
    Session["WorkingList"] = q.Select( x => new { x.RefID } );
    

    On the details page, I need to be able to access the Session["WorkingList"] such that I can use the Linq provided by this StackOverFLow question to find the next and previous records, which will be something like:

    var workingList = (IEnumerable<dynamic>) Session["WorkingList"];
    var nextRecord = workingList.SkipWhile(i => i.RefID != currentRecord).Skip(1).First();
    

    I know that db.Query returns a IEnumerable< Object>, but I'm guessing what's really coming back is a IEnumerable< dynamic >. And that works, but seems overly complicated. Is there a better way?

  • Knox
    Knox over 12 years
    Interesting, is the "as" the modern way of casting?
  • Yuck
    Yuck over 12 years
    @Knox In a sense, yes. Using the as keyword will try to cast to the specified type. You're guaranteed that the variable will be a reference of that type. If the cast fails the result will be null. There is a corresponding is keyword that returns a bool if the object is the specified type. I believe both keywords were added in version 2.0 of the framework.