Wednesday, April 13, 2011

Linq Fetch all controls (ordered)

Is there a way to fetch all the control using linq.

What I'll like to do is something like that (order the control by tab index) :

foreach (Control control in this.Controls.OrderBy(c => c.TabIndex)
{
    ...
}

I use that kind of query when I got a List<...>

I use c# and .Net 3.5

From stackoverflow
  • ControlCollection only implements IEnumerable, not IEnumerable<T>. That's easy to fix though - add a call to Cast():

    foreach (Control control in Controls.Cast<Control>()
                                        .OrderBy(c => c.TabIndex))
    {
    }
    

    Or you could use a query expression, which will call Cast() where necessary:

    var controls = from Control c in Controls
                   orderby c.TabIndex
                   select c;
    
    foreach (Control control in controls)
    {
    }
    
    Chris Shaffer : Note: TabIndex is on WebControl, so replace all "Control" with "WebControl".
    Melursus : TabIndex is also on WinControl. Thx for that quick answer!
    Chris Shaffer : Oops, spend all your time in one world and you forget the others exist :)

0 comments:

Post a Comment