Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do this using linq? [duplicate]

Possible Duplicate:
LINQ equivalent of foreach for IEnumerable<T>

please help me to figure out how to replace the loop below with a linq expression:


using System.Web.UI.WebControls;
...
Table table = ...;
BulletedList list = new BulletedList();

foreach (TableRow r in table.Rows)
{
    list.Items.Add(new ListItem(r.ToString()));
}

this is a contrived example, in reality i am not going to convert rows to strings of course.

i am asking how to use BulletedList.AddRange and supply it an array of items created from table using a linq statement.

thanks! konstantin

like image 521
akonsu Avatar asked Aug 03 '26 18:08

akonsu


2 Answers

Consider using AddRange() with an array of new ListItems. You'll have to .Cast() to get an IEnumerable of TableRow.

  list.Items.AddRange(
         table.Rows.Cast<TableRow>()
                   .Select(x => new ListItem(x.ToString()))
                   .ToArray()
   );
like image 135
p.campbell Avatar answered Aug 05 '26 08:08

p.campbell


how about

list.Items.AddRange(table.Rows.Select(r => new ListItem(r.ToString())));
like image 45
theburningmonk Avatar answered Aug 05 '26 06:08

theburningmonk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!