我想为二维for loop
编写这样的双List
,它会抛出错误cannot be assigned to it is read only
然后如何修改它?(也许我们可以构建一个新变量,但是PositionList
的类型非常复杂)顺便说一下,有一种简单的方法可以使用linq
来更改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;
}
}
}
以下是PositionList
,pairList
和AddTwoList
已存在列表的代码:
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();
答案 0 :(得分:1)
所以
if
语句中创建新对象,否则linq不是方向。cannot be assigned to it is read only
的错误 - 您正在使用的对象集合由linq生成,是匿名类型的集合。 匿名类型的属性为read-only
,用于解释错误。没有进入你的linq逻辑,最简单的解决方法是创建一个类,你的linq将初始化它的实例而不是匿名类型:
public class YourClass
{
public int Position { get; set; }
public int DesignPosition { get; set; }
}
var PositionList = pairList.GroupBy(o => o.pair.Item1.Date)
.Select(o => AddTwoList.GroupBy(p => p.Key)
.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;
}
}
}