How to do this using linq?

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

please help me figure out how to replace the loop below with the 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 fact, I am not going to convert strings to strings, of course.

I ask how to use BulletedList.AddRange and provide it with an array of elements created from the table using the linq statement.

thank! Konstantin

+3
source share
2 answers

Consider using AddRange()with an array of new ones ListItems. You need to .Cast()get IEnumerableout TableRow.

  list.Items.AddRange(
         table.Rows.Cast<TableRow>()
                   .Select(x => new ListItem(x.ToString()))
                   .ToArray()
   );
+1
source

What about

list.Items.AddRange(table.Rows.Select(r => new ListItem(r.ToString())));
+1

Source: https://habr.com/ru/post/1759547/


All Articles