Do you look for opportunities to use Linq?

Last updated by Brady Stroud [SSW] 7 months ago.See history

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

Adam Cogan
Damian Brady
We open source.Loving SSW Rules? Star us on GitHub. Star
Stand by... we're migrating this site to TinaCMS