Why use LINQ

I was asked “Why I never used LINQ?”   I guess the real answer was, I never thought about it.  I really had no good reason for not using LINQ other it was new and unfamiliar.  When I finally used LINQ; I found I was getting rid of old habits and making code simpler and cleaner.

Example of code written in C#:

foreach (Charges charge in (ary))
{
if (charge.ChargeDescription.ToLower().Contains("total"))
{
ary.Remove(charge);
}
}

Code converted to LINQ:

var rslt = from Charges charge in ary where charge.ChargeDescription.ToLower().Contains("total") select charge;

while(rslt.Count() > 0)
{
Charges chargese = rslt.ElementAt(0);
ary.RemoveAt(ary.IndexOf(Chargese));
}

To this day I still use C# with a little LINQ to simplify my code.   I use LINQ for validations, quick look up and data manipulations.  It is definitely a change from what I used to do, but worth learning.  What I like about the above code is I had eliminated the nested if without complicating the code.

Using LINQ to find a control in the ControlCollection

While writing a windows application in C#, I realized that there was no find control method in the ControlCollection class. This was a problem as it would create a significant amount of code to find a control. Well it turns out you can do it using LINQ. I had found a blog that I was able to implement the code fairly cleanly. The original code limited me a little bit, but with a very minor modification I came up with this code.

Original Blog: linq-the-uber-findcontrol

public static class PageExtensions
{
public static IEnumerable All(this Control.ControlCollection controls)
{
foreach (Control control in controls)
{
if (control.HasChildren)
{
foreach (Control child in control.Controls.All())
{
yield return child;
}
}
else
{
yield return control;
}
}
}
}

private Control GetControlByName(string name)
{
Control firstEmpty = this.Controls.All()
.OfType()
.Where(tb => tb.Name.Trim().Equals(name))
.FirstOrDefault();
return firstEmpty;
}