gpt4 book ai didi

c# - 索引超出范围。必须是非负数且小于集合的大小

转载 作者:太空狗 更新时间:2023-10-29 23:17:46 25 4
gpt4 key购买 nike

我正在尝试在 for 循环中添加一个列表。

这是我的代码我在这里创建了一个属性

    public class SampleItem
{
public int Id { get; set; }
public string StringValue { get; set; }
}

我想从另一个列表中添加值

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;
}

有人可以更正我的代码吗。

最佳答案

您得到一个超出范围的索引,因为当 sampleItem 没有项目时,您指的是 sampleItem[i]。你必须 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
});
}

关于c# - 索引超出范围。必须是非负数且小于集合的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7688435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com