Nishant Rambhojun
Nishant Rambhojun

Reputation: 77

Foreach loop failing

enter image description here

When I debug I get the above data.

Now I am trying to loop through those so as to fill a list (that will be used to populate my model)

However, I get the following error:

enter image description here

Any ideas as to why?

Upvotes: 0

Views: 103

Answers (1)

Elian Ebbing
Elian Ebbing

Reputation: 19027

You get this problem because you try to add an item to the list you are looping through. This is not allowed.

At first glance it looks like you add the item to a different list, but this is not the case: in the first foreach loop you copy references to products from result to lst. These are just references you copy, so the products in lst are the same products as in result. This means that lst.Products.FirstOrDefault() returns the same object as result.Products.FirstOrDefault().

Upvotes: 3

Related Questions