2011-10-07 69 views
5

我试图在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; 
} 

增值有人可以纠正我的代码,请。

回答

5

您得到的索引超出范围,因为当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 
    }); 
} 
+0

哇!多谢你们。只有一分钟,我得到了8个回应!这就是我喜欢这个地方的原因!我试过了,它的作用就像魅力:) – HardCode

0
List<SampleItem> sampleItem = new List<SampleItem>(); // Error: Index out of range 
for (int i = 0; i < otherListItem.Count; i++) 
{ 
    sampleItem.Add(new sampleItem()); // add this line 
    sampleItem[i].Id = otherListItem[i].Id; 
    sampleItem[i].StringValue = otherListItem[i].Name; 
} 
0

一个List必须Add版到;如果尚未创建索引项目,则无法将其索引项目设置为值。你需要的东西,如:

List<SampleItem> sampleItems = new List<SampleItem>(); 
for (int i = 0; i < otherListItem.Count; i++) 
{ 
    SampleItem si = new SampleItem 
    { 
     Id = otherListItem[i].Id, 
     StringValue = otherListItem[i].Name 
    }; 
    sampleItems.Add(si); 
} 
0
List<SampleItem> sampleItem = new List<SampleItem>(); 
foreach(var item in otherListItem) 
{ 
sampleItem.Add(new SampleItem { Id = item.Id, StringValue = item.Name}); 
} 
0

在你的for循环试着像这样的东西代替你有什么:

SampleItem item; 
item.Id = otherListItem[i].Id; 
item.StringValue = otherListItem[i].StringValue; 
sampleItem.add(item); 
0

使用

List<SampleItem> sampleItem = (from x in otherListItem select new SampleItem { Id = x.Id, StringValue = x.Name }).ToList(); 
0

做以下操作:

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

} 
0

由于您从不将任何项目添加到sampleItem列表中,您会收到错误消息。

这样做的更好的方式是使用LINQ(未经测试)

var sampleItem = otherListItem.Select(i => new SampleItem { Id= i.Id, StringValue = i.Name}).ToList(); 
0

//使用System.Linq的;

otherListItem.ToList().Foreach(item=>{ 
    sampleItem.Add(new sampleItem{ 
}); 
0

它发生在我身上,因为我在Mapper类中映射了一个列两次。 在我的情况下,我只是简单地分配列表元素。 例如

itemList item; 
ProductList product; 
item.name=product.name; 
item.price=product.price; 
相关问题