C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Example 1: First we see the LINQ code version. It uses the var implicit type keyword for simpler syntax.
VarExample 2: Here is a different version of our method. LINQ allows you to write database-like queries on various objects, including Windows Form controls.
Example 3: Here we look at a method that doesn't use LINQ. It tests every control for whether it is a TextBox and has focus. This is imperative code.
ForeachWindows Forms and OfType method: C#
/// <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();
}
Using foreach-loop: C#
/// <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;
}
}
}
Using is-operator: C#
/// <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;
}
}
}
Using as-operator: C#
/// <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;
}
}
}
}
Output
Foreach: 780 ms
LINQ version: 889 ms