开发者

C#, Foreach Item In

I have a Listbox, which houses some items. The Items are Grids which house a variety of Textblocks, buttons, etc etc.

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

Yet this throws an exception because there are other items th开发者_StackOverflow社区an Textblock's in there. How can I accomodate this? Thanks.


As I read it, the problem here is with the inner loop, and there being things in Children that are not TextBlocks.

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
}


you could try

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

for your inner loop.

EDIT: TIL, that this can also be written as:

foreach (TextBlock in thisTextblock in thisGrid.Children.OfType<TextBlock>());


foreach (var thisTextblock in thisGrid.Children)
                            {
                                 if(thisTextblock is Textblock)
                                     //Do Somthing
                            }


If LINQ is available try that:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜