简体   繁体   中英

IEnumerable doesn't Add items

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?

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM