Question

Why an IEnumerable is not adding items?

this code add itens 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 itens:

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

Any idea?

Was it helpful?

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

OTHER TIPS

All of these will give you an IEnumerable<string>:

You can use an explicit constructor to build and populate your collection:

  • new List<String>( ddlTransportadora.Items.Select( x => x.Value ) )

You can use LINQ to create an enumerable collection on the fly:

  • ddlTransportadora.Items.Select( x => x.Value ).ToList()
  • ddlTransportadora.Items.Select( x => x.Value ).ToArray()

You can even skip creating an actual collection and simply use LINQ deferred execution to provide an enumerable view of your data:

  • ddlTransportadora.Items.Select( x => x.Value )

Why try to make things any more complicated than they need to be?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top