'List <T> .ForEach ()' and volatility

I want to translate all the points in List<T>. It works:

for (int i = 0; i <PolygonBase.Count; ++i) 
{
    PolygonBase[i] = PolygonBase[i] + MousePos;
}

But using List<T>.ForEachnot:

PolygonBase.ForEach(v => v += MousePos);

Ideas?

+5
source share
2 answers

Your current code simply reassigns the local variable vto the new value - it does not refer to the original value in the list. This is equivalent to writing:

foreach(int v in PolygonBase)
{
    v += MousePos;
}

To return to the original value, use ConvertAll:

PolygonBase.ConvertAll(v => v += MousePos);
+11
source

ForEach is not changed, it does not change the data structure. Check out this threat. Using conditional lambda operators with foreach List action

0

All Articles