Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 664
user3014311 Avatar asked Nov 18 '25 22:11

user3014311


1 Answers

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
}
like image 167
Josh Avatar answered Nov 20 '25 11:11

Josh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!