0

I ran across a weird issue, but there is certainly a miss from my side. Check if you can point that out. I was doing this in foreach loop but then I switched to a for loop to avoid looping ambiguities, but still it fails.

// Update each quantum.
for (int i = 0; i < Quantums.Where(a => a.Language != "en-US").Count(); i++)
{
    Quantums[i].ListQType.AddRange(AddedOnes);
}

What happens is that the list AddedOnes gets added to all quantums in Each iteration and not only to the one we are dealing in the loop body. I suspect references mess. Any pointers?

Thanks

tariq
  • 2,193
  • 15
  • 26

2 Answers2

1

Calling Quantums[i] is the problem. The filtered list will have different indexes and the orignal list will have different index i. Here you are modifying the original list with the the index of the filtered list.

Better use the for-each lambda expression or the for-each loop.

Quantums.Where(a => a.Language != "en-US").ForEach(x=>x.ListQType.AddRange(AddedOnes));

or

foreach(var item in Quantums.Where(a => a.Language != "en-US").)
{
   item.ListQType.AddRange(AddedOnes);
}
Carbine
  • 7,849
  • 4
  • 30
  • 54
  • Already tried the Lambda for-each, I think i need to check why ListQType for each quantum is pointing to same thing. – tariq Feb 24 '16 at 05:50
1

This might not have caused your problem, but your for loop's condition seems wrong. If you're going to do a Where() on the condition, you should make sure the list you are working on in the for loop is on the same condition.

I suspect references mess

However, in spite of that, as you suspect, each of your Quantums seem to refer to the same object. It's probably in the way you created each object. I suspect you were doing something like:

Quantum q1 = new Quantum(){Property1=something /*etc*/};
Quantum q2 = q1; // assuming your Quantums is a list of Quantum

Or it could be just the ListQType that is reference copied on each of the elements of your Quantums.

You should look into deep copying, or at least instantiate new objects and copy values individually (safe if they are value types) if that was what you were trying to do.

Community
  • 1
  • 1
Tyress
  • 3,573
  • 2
  • 22
  • 45
  • 1
    The case was that where the Quantums list was being created, same ListQtype was being assigned in a loop. Hence all quantum.ListQType refer to same location. Thanks. – tariq Feb 24 '16 at 06:02