views:

88

answers:

3

hello,

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

+1  A: 

how about

list.Items.AddRange(table.Rows.Select(r => new ListItem(r.ToString())));
theburningmonk
i cannot apply Select to table.Rows, can i?
akonsu
that was my bad, just wrote something down as an idea, as p.campbell pointed out, you'd need to cast first, and then call ToArray() at the end
theburningmonk
+1  A: 

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()
   );
p.campbell