-2

I have a list of objects which gets when updated using linq ForEach. Problem is that data is getting updated with reference type. I want to update it with value type

I tried to do cloning but it didn't work (not sure whether I'm following the right procedure).

Leo
  • 136
  • 2
  • 2
  • 11

1 Answers1

1

Your list newSetRatio is emptied inside if condition. If that condition returns false, it will contain the values from previous iteration. Since it is populated in every iteration, outside of condition, whenever condition returns false all items from assetSharingRatios will be added without list being cleared previously. So in case assetSharingRatios has not changed and your codnition returns false, newSetRatio will have all duplicates. And if condition keeps resulting in false, items in newSetRatio will triple and so on.

Another point is your last line of code contributePartnersData.assetSharingRatio = newSetRatio; If you fix newSetRatio behavior, then last item added into contributingPartnersData will get new assetSharingRatio values whenever if condition is false. Not sure if this is intended, looks a bit strange. Is this why those last three lines of code are outside of 'if`?

Marko Stanojevic
  • 418
  • 5
  • 15
  • I tried placing the line `newSetRatio = new List();` outside the if condition but it didn't work and whenever I change the value of a list `newSetRatio` it also affects `assetSharingRatio` the problem is similar to the problem in this [link](https://stackoverflow.com/questions/13977841/how-do-i-change-my-new-list-without-changing-the-original-list) but I tried the solution provided there but it didn't work – Leo Aug 19 '17 at 23:02
  • Sorry, I misunderstood your problem. So when you do `.Foreach` on `newSetRatio' it updates values in `assetSharingRatios` and that is a problem? If so, then change `newSetRatio.AddRange(assetSharingRatios.Where....` into `newSetRatio = new List(assetSharingRatios.Where...` and let me know if that helps – Marko Stanojevic Aug 20 '17 at 21:34