C #, Foreach Item In

I have a Listbox that stores some items. Elements are grids in which various text blocks, buttons, etc. are placed. Etc.

foreach (Grid thisGrid in myListBox.SelectedItems) { foreach (TextBlock thisTextblock in thisGrid.Children) { //Do Somthing } } 

However, this throws an exception, since there are other elements besides Textblock. How can I post this? Thanks.

+4
source share
4 answers

As I read it, the problem here is that there is an inner loop, and there are things in Children that are not TextBlock s.

If LINQ is available:

 foreach (TextBlock thisTextblock in thisGrid.Children.OfType<TextBlock>()) { // ... do something here } 

otherwise:

 foreach (object child in thisGrid.Children) { TextBlock thisTextblock = child as TextBlock; if(thisTextblock == null) continue; // ... do something here } 
+13
source

you can try

 foreach (TextBlock thisTextblock in thisGrid.Children.Where(c => c is TextBlock)) { /* ... */ } 

for your inner cycle.

EDIT : TIL that it can also be written as:

 foreach (TextBlock in thisTextblock in thisGrid.Children.OfType<TextBlock>()); 
+3
source
 foreach (var thisTextblock in thisGrid.Children) { if(thisTextblock is Textblock) //Do Somthing } 
0
source

If LINQ is available, try the following:

 thisGrid.Children.OfType<TextBlock>().ToList().ForEach(tb => { ...your code here }); 
0
source

All Articles