I am using Foreach to loop all Controls within a win form. However, Foreach always arranges the Controls in alphabetical order.
I tried to set the tab index and also change the sequence of the Controls’ code. However, the loop is still in alphabetical order.
Is there some methods for looping Controls in a winform with specific order?
Using the LINQ extension-method
.OrderBy()(and companion.OrderByDescending()) you can use any ordering you want.But because
Controlsis a non-generic collection, you need to convert it to a generic variant first. This can be done with either.OfType<T>()(filters) or.Cast<T>()(casts).If you need to modify the collection as you go, you can use
.ToList()to make a snapshot.You will need to import the LINQ namespace to enable the extension-methods.