Use LINQ to find specific Windows Forms controls. You must iterate through Windows controls and find the first matching control. Efficiently find the first focused TextBox in a Windows Forms window.
Here we implement a loop on the Windows controls in different ways. First I show the LINQ version. It uses the var keyword for simpler syntax.
/// <summary>
/// Use a LINQ query to find the first focused text box on a windows form.
/// </summary>
public TextBox TextBoxFocusedFirst1()
{
var res = from box in this.Controls.OfType<TextBox>()
where box.Focused == true
select box;
return res.First();
}LINQ allows you to write database-like queries on various objects, including Windows Form controls. We would like to test the performance penalty with LINQ, so here is a different version of our method.
/// <summary>
/// Use a combination of methods to find the right TextBox.
/// </summary>
public TextBox TextBoxFocusedFirst2()
{
foreach (TextBox t in mainForm.Controls.OfType<TextBox>())
{
if (t.Focused == true)
{
return t;
}
}
}Here we look at a method that doesn't use and LINQ. It uses the equivalent old-style code, which tests every control for whether it is a TextBox and has focus.
/// <summary>
/// Classic code to search form collections.
/// </summary>
public TextBox TextBoxFocusedFirst3()
{
foreach (Control con in mainForm.Controls)
{
if (con is TextBox && con.Focused == true)
{
return con as TextBox;
}
}
}| Version ID | Description | Time in ms for 100,000 iterations Repeated 4 times |
| 1 | LINQ version | 889 |
| 3 | Classic version | 780 |
After taking the above benchmarks, I did a bit more tinkering and I found an even better version. This version will avoid 1 cast and performs about 10% better than the second version. Note that it doesn't use any LINQ.
/// <summary>
/// Classic code to search form collections.
/// </summary>
public TextBox TextBoxFocusedFirstX()
{
foreach (Control con in mainForm.Controls)
{
if (con.Focused == true)
{
TextBox textBox = con as TextBox;
if (textBox != null)
{
return textBox;
}
}
}
}Avoiding the LINQ syntax and OfType is faster. So, my recommendation is this: Don't use LINQ just because it is there. However, if it makes your life easier and you like how it looks or is more maintainable to you, use it. It doesn't have a large penalty.