我正在尝试在for循环中添加一个列表.
这是我的代码, 我在这里创建了一个属性
public class SampleItem
{
public int Id { get; set; }
public string StringValue { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我想从另一个列表中添加值
List<SampleItem> sampleItem = new List<SampleItem>(); // Error: Index out of range
for (int i = 0; i < otherListItem.Count; i++)
{
sampleItem[i].Id = otherListItem[i].Id;
sampleItem[i].StringValue = otherListItem[i].Name;
}
Run Code Online (Sandbox Code Playgroud)
有人可以更正我的代码.
你得到一个超出范围的索引,因为你指的是sampleItem[i]什么时候sampleItem没有项目.你必须的Add()物品......
List<SampleItem> sampleItem = new List<SampleItem>();
for (int i = 0; i < otherListItem.Count; i++)
{
sampleItem.Add(new SampleItem {
Id = otherListItem[i].Id,
StringValue = otherListItem[i].Name
});
}
Run Code Online (Sandbox Code Playgroud)