Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index was out of range. Must be non-negative and less than the size of the collection

Tags:

c#

I'm trying to add a list in the 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 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 correct my code please.

like image 449
HardCode Avatar asked Oct 07 '11 14:10

HardCode


1 Answers

You get an index out of range because you're referring to sampleItem[i] when sampleItem has no items. You must 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 
    });
}
like image 66
canon Avatar answered Sep 27 '22 19:09

canon