Search code examples
c#.netlistloopsienumerable

IEnumerable doesn't Add items


Why an IEnumerable is not adding items?

This code add items to "values" list:

List<String> values = new List<String>();

for (int i = 0; i < ddlTransportadora.Items.Count; i++)
{
    values.Add(ddlTransportadora.Items[i].Value);
}

But this code makes the loop, and after values doesn't have items:

IEnumerable<String> values = new List<String>();

for (int i = 0; i < ddlTransportadora.Items.Count; i++)
{
    values.Add(ddlTransportadora.Items[i].Value);
}

Any idea?


Solution

  • Because the Add method defined in IList<T> interface, and IEnumerable<T> doesn't inherit from IList<T>.You can use this instead:

    IList<String> values = new List<String>();
    for (int i = 0; i < ddlTransportadora.Items.Count; i++)
    {
        values.Add(ddlTransportadora.Items[i].Value);
    }