user6703592 - 1 year ago 74
C# Question

# Change the value in the double for loop or use linq

I want to write such double

`for loop`
for a two dimensional
`List`
, it threw a error
`cannot be assigned to it is read only`
then how to modify it?(Maybe we can build a new variable, but the type of
`PositionList`
is very complicated) By the way, is there a easy way to use the
`linq`
to change the
`List`
?

``````for (int i = 0; i < PositionList.Count - 1; i++)
{
for (int j = 0; j < PositionList[i].Count; j++)
{
if (Math.Abs(PositionList[i][j].DesignPosition - PositionList[i][j].Position) < T)
{
PositionList[i][j].DesignPosition = PositionList[i][j].Position;
PositionList[i + 1][j].Position = PositionList[i][j].DesignPosition;
}
}
}
``````

Here is the code for the
`PositionList`
,
`pairList`
and
`AddTwoList`
are existed Lists:

``````var PositionList = pairList.GroupBy(o => o.pair.Item1.Date)
.Select(o =>
{
int Position = 0;
var SumPosition = AddTwoList.GroupBy(p => p.Key)
.Select(p => new {
DesignPosition = p.Sum(q => q.DesignPosition),
Position
}).ToList();
return SumPosition;
}).ToList();
``````

An alternative way to obtain the result:

``````int Position = 0; //0 day default as 0
int RememberPreviousDesign = 0; //remember yesterday's DesignPosition
var SumPosition = AddTwoList.GroupBy(p => p.Key) //Sum the total list
.Select(p =>  {
int DesignPosition = p.Sum(q => q.DesignPosition);
Position = RememberPreviousDesign;
if (Math.Abs(DesignPosition - Position) < T)
{
DesignPosition = Position;
}

RememberPreviousDesign = DesignPosition;
``````

So

1. As far as for using linq to update the objects - linq is for querying and not updating, so unless you want to create new objects in the `if` statement linq is not the direction.
2. As for your error of `cannot be assigned to it is read only` - The collection of objects you are using is generated by linq and is a collection of an anonymous type. Anonymous type's properties are `read-only`, which explains the error.

Without going into your linq logic the easiest way to solve is to create a class and that your linq will initialize instances of it instead of an anonymous type:

``````public class YourClass
{
public int Position { get; set; }
public int DesignPosition { get; set; }
}

var PositionList = pairList.GroupBy(o => o.pair.Item1.Date)
.Select(p => new YourClass {
DesignPosition = p.Sum(q => q.DesignPosition),
Position = 0
}).ToList())
.ToList();

for (int i = 0; i < PositionList.Count - 1; i++)
{
for (int j = 0; j < PositionList[i].Count; j++)
{
if (Math.Abs(PositionList[i][j].DesignPosition - PositionList[i][j].Position) < T)
{
PositionList[i][j].DesignPosition = PositionList[i][j].Position;
PositionList[i + 1][j].Position = PositionList[i][j].DesignPosition;
}
}
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download