Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying a property of an object inside of a foreach loop doesn't work?

Tags:

c#

.net

foreach

This is puzzling me. I'm using PetaPoco to retreive some values from a database, and then looping over them and retrieving a value to assign to one of the properties of each object.

    public IEnumerable<RetreaveIndex> FillResults(IEnumerable<RetreaveIndex> results)
    {
        //add the associated users
        foreach (RetreaveIndex index in results)
        {
            index.AssociatedUsers = _registeredUserDao.GetUsersByIndex(index).ToList();
        }
        return results;
    }

When I set a breakpoint during the foreach loop, the AssociatedUsers property is being set correctly. during foreach loop

but then in a breakpoint at the end of the loop, it didn't save it? enter image description here

I'm confused, shouldn't Index be a reference to a place in memory which is being modified? It's an object after all. What am I missing here?

like image 592
RodH257 Avatar asked May 21 '11 12:05

RodH257


3 Answers

  1. What is the IEnumerable implementation? Could it be returning a copy of the object?

  2. Is RetreaveIndex a struct, and thus a value type? If so, then the variable index will be a copy.

like image 199
Dark Falcon Avatar answered Oct 20 '22 01:10

Dark Falcon


Depending on how the IEnumerable passed in is implemented, it has no requirement that the next time it enumerates over the data that it return the same objects as before. Try turning the IEnumerable into a List before the foreach loop and return that insead.

like image 44
Ed Marty Avatar answered Oct 19 '22 23:10

Ed Marty


From the project web site:

Query vs Fetch

The Database class has two methods for retrieving records Query and Fetch. These are pretty much identical except Fetch returns a List<> of POCO's whereas Query uses yield return to iterate over the results without loading the whole set into memory.

In other words, Query re-loads the values from the backing store each time, and doesn't keep an item around after it's been enumerated. When you go look at an item again after the end of your loop, that item is re-loaded from the backing store.

like image 36
Jim Mischel Avatar answered Oct 20 '22 01:10

Jim Mischel