Home > other >  Why is my IEnumerable variable also getting updated?
Why is my IEnumerable variable also getting updated?

Time:03-21

I am a little confused about why the logic here isn't working, and I feel like I have been staring at this bit of code for so long that I am missing something here. I have this method that gets called by another method:

  private async Task<bool> Method1(int start, int end, int increment, IEnumerable<ModelExample> examples)
        {
                for (int i = start; i<= end; i  )
                {
                   ModelExample example = examples.Where(x => x.id == i).Select(i => i).First();
                   example.id = example.id   increment; //Line X
                   // do stuff

                }

                return true;

        }

I debuged the code above and it seems like when "Line X" gets executed not only is example.id changed individually but now that example in the List "examples" gets updated with the new id value. I am not sure why? I want the list "examples" to remain the same for the entirety of the for loop, I am confused why updating the value for example.id updates it in the list as well?

(i.e. if the list before "Line X" had an entry with id = 0, after "Line X" that same entry has its id updated to 1, how can I keep the variable "examples" constant here?)

Any help appreciated, thanks.

CodePudding user response:

This is what your list looks like:

 ---------------    
| List examples |            ----------- 
 ---------------            |  Example  |
|               |            ----------- 
|     [0] --------------->  | Id: 1     |
|               |           | ...       |
 ---------------             ----------- 
|               |           
|     [1] --------------->   ----------- 
|               |           |  Example  |
 ---------------             ----------- 
|               |           | Id: 2     |
|     ...       |           | ...       |
|               |            ----------- 
 --------------- 

In other words, your list just contains references to your examples, not copies. Thus, your variable example refers to one of the entities on the right-hand side and modifies it in-place.

If you need a copy, you need to create one yourself.

CodePudding user response:

An IEnumerable, unlike an Array, is lazy evaluated. That means every time you try to access the IEnumerable list it is possible that the order of the output isnt the same as before.

  •  Tags:  
  • c#
  • Related