Home
Do you look for opportunities to use Linq?
  v3.0 Posted at 12/02/2013 11:38 PM by Tiago Araujo

Linq is a fantastic addition to .Net which lets you write clear and beautiful declarative code. Linq allows you to focus more on the what and less on the how.

You should look for opportunities to replace your existing code with Linq.

​For example, replace your foreach loops with Linq.

var lucrativeCustomers = new List<Customer>();
foreach (var customer in Customers)
{
    if (customer.Orders.Count > 0)
    {
        lucrativeCustomers.Add(customer);
    }
}
Figure: Bad Example - imperative programming using a foreach loop
var lucrativeCustomers = Customers.Where(c => c.Orders.Count > 0).ToList();
Figure: Good Example - declarative programming using Linq

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address:

    Comments: