3

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

Community
  • 1
  • 1
akonsu
  • 28,824
  • 33
  • 119
  • 194
  • @aksonu: Welcome to StackOverflow! Please vote-up answers that are helpful to you, and mark answers as accepted (click the checkmark) for that which helped you the most. This is the reputation system that helps improve your reputation, as well as ensure quality answers to your questions. – p.campbell Aug 13 '10 at 15:45
  • @aksonu: remember to upvote answers that you find helpful at StackOverflow - the grey triangles above/below each answer's score. Not fishing for upvotes, just trying to help out! :) This applies to all answers, even those that aren't on questions that you've asked! – p.campbell Aug 13 '10 at 15:53
  • cannot. not enough reputation :) thanks for your help. – akonsu Aug 13 '10 at 15:54
  • See http://stackoverflow.com/questions/200574/linq-equivalent-of-foreach-for-ienumerable – Brandon Montgomery Aug 13 '10 at 15:20

2 Answers2

2

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
  • 98,673
  • 67
  • 256
  • 322
1

how about

list.Items.AddRange(table.Rows.Select(r => new ListItem(r.ToString())));
theburningmonk
  • 15,701
  • 14
  • 61
  • 104