2011-10-07 6 views
5

Estoy tratando de agregar una lista en el ciclo for.El índice estaba fuera de rango. Debe ser no negativo y menor que el tamaño de la colección

Aquí está mi código creé una propiedad aquí

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

Quiero añadir valor a partir de otra lista

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

Puede alguien corregir mi código por favor.

Respuesta

5

Obtiene un índice fuera del intervalo porque se está refiriendo a sampleItem[i] cuando sampleItem no tiene elementos. Debe Add() artículos ...

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

¡Guau! Gracias chicos. ¡Solo un minuto y obtuve 8 respuestas! ¡Es por eso que amo este lugar! Lo probé y funciona como un encanto :) – 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

Un List debe ser Add ed a; no puede simplemente establecer sus elementos indexados en valores si aún no se han creado. Es necesario algo así como:

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

En el bucle intenta reemplazar lo que tienes con algo como esto:

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

uso

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

do siguiente:

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

Obtiene el error ya que nunca agrega ningún elemento a la lista de elementos de muestra.

una mejor forma de hacer esto sería utilizar LINQ (no probado)

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

// usando System.Linq;

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

Me pasó porque había mapeado una columna dos veces en la clase Mapper. En mi caso, simplemente estaba asignando elementos de lista. p.

itemList item; 
ProductList product; 
item.name=product.name; 
item.price=product.price; 
Cuestiones relacionadas