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.
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 
    });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With