2011-10-07 44 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; 
相關問題