Hi, I have the following code causing strange behavior. The instance property of objects contained in IEnumerable created by linq to Objects is not updated in subsequent foreach operations. The foreach statement must include IEnumerable. Instead, the solution should list it earlier.
Although I found a solution, I did not see this documented anywhere in the books or in articles dealing with similar examples. Perhaps someone with intricate linq knowledge can explain this.
It took me a day to pinpoint the cause of the error and not easily debugged in a large application. Then I reproduced it in a much simpler environment, presented below.
public class MyClass { public int val ; } public class MyClassExtrax { public MyClass v1 { get; set; } public int prop1 { get; set; } } void Main() { List <MyClass> list1 = new List<MyClass>(); MyClass obj1 = new MyClass(); obj1.val = 10; list1.Add(obj1); MyClass obj2 = new MyClass(); obj2.val = 10; list1.Add(obj2); IEnumerable<MyClassExtrax> query1 = from v in list1 where v.val >= 0 select new MyClassExtrax{ v1=v , prop1=0 } ;
Output: in list 1, the value is 40:
in list 1, the value is 40:
in the MyClassExtra list, v1.val is 40, prop1 is 0
in the MyClassExtra list, v1.val is 40, prop1 is 0
As you can see, prop1 is not updated to 40. !!
source share