Search code examples
c#listobjectforeachtempdata

Loop foreach over List of objects (cannot operate on variables of type 'object')


I am trying to save some objects into a list for later use. Here is how I store them:

List<Engagement> engagementsList = new List<Engagement>();

foreach (Engagement engagement in db.Engagements)
{
    // Implementation here
}

TempData["DeletedE"] = engagementsList;
TempData.Keep();

Then, I am trying iterate over the list, but I get the error:

cannot operate on variables of type 'object'

I am iterating over the list by:

foreach (Engagement e in TempData["DeletedE"])
{
    // Implementation here...
}

Any help is greatly appreciated.


Solution

  • MVC's TempData[] indexer returns an object, over which you cannot iterate.

    You need to cast it to the same type that you store in it:

    foreach (var engagement in (List<Engagement>)TempData["DeletedE"])
    {
    }
    

    This is also explained in how to access an array element from tempdata.