user3014311
user3014311

Reputation: 448

how to loop through a session object which is a list

I have a session object, which contains a list of objects..

Session.Add("errorlist",errorlist);

Now i want to loop through this errorlist in another function. I tried, but it gives following error:

foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'

This is what I tried:

var error = Session["errorlist"];
foreach (var item in error)
{
    //Something here
}

I can see a list of objects in "error" variable.

Upvotes: 2

Views: 5476

Answers (1)

Josh
Josh

Reputation: 44906

Everything that goes into session is of type System.Object by default. So your var statement will not have the correct type.

You need to cast it when pulling back out of session.

var error = (List<MyObject>)Session["errorlist"];

A better way would be to use a safe cast and check for null:

var error = Session["errorlist"] as List<MyObject>;

if(error != null){
   //Do stuff here
}

Upvotes: 9

Related Questions