The index was out of reach. Must be non-negative and smaller than the size of the collection

I am trying to add a list to a for loop.

Here is my code I created a property here

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

I want to add a value from another list

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

Can someone fix my code please.

+5
source share
10 answers

You get an index out of range because you mean sampleItem[i]when sampleItemit has no elements. You need Add()items ...

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 
    });
}
+5
source
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
source

A List Add ed to; , . - :

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

you get an error because you never add items to the sampleItem list.

the best way to do this would be to use linq (untested)

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

// using system.linq;

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

This happened to me because I mapped the column twice in the Mapper class. In my case, I just assigned list items. eg

itemList item;
ProductList product;
item.name=product.name;
item.price=product.price;
0
source

All Articles