by

Eliminate (some) for loops using .NET Language-Integrated Queries (LINQ)

Loops can be tedious to write, so why not try to reduce the amount of time spent writing them? They are also a pain to debug, and to try to read. In order to write highly readable code, I propose eliminating the use of loops whenever possible.

This blog post covers the basics of .NET Language-Integrated Queries or LINQ for short.

So what is LINQ? According to MSDN:

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support. Furthermore, you have to learn a different query language for each type of data source: SQL databases, XML documents, various Web services, and so on. With LINQ, a query is a first-class language construct, just like classes, methods, events.

Whoa, hold on…

You read that right. LINQ can be used to query a multitude of types of datasets, including SQL databases, XML documents, and even just plain old objects.

But what does LINQ even look like and how can it help us eliminate for loops? Let’s take a look at LINQ to objects to get a feel for the facilities of LINQ.

Here is some code that initializes a List<T> of Person objects, each with a “Name” and an “Age” field associated with it. The code then loops through the List<Person> and on each iteration checks the Name of the Person looking for individuals with a name that begins with the letter W. When it finds a Person whose name begins with W it saves it into another List<Person>. At the end of the program there is another loop that goes through the List<Person> with Names beginning with W and prints their names to the console window.

The Code:

//here is the Person class

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

//here is the Main method

class Program
{
    static void Main(string[] args)
    {
        List<Person> people = new List<Person>();
        Person dave = new Person()
        {
            Name = "Dave",
            Age = 28
        };
        people.Add(dave);
        Person arthur = new Person()
        {
            Name = "Arthur",
            Age = 31
        };
        people.Add(arthur);
        Person windell = new Person()
        {
            Name = "Windell",
            Age = 38
        };
        people.Add(windell);
        Person quentin = new Person()
        {
            Name = "Quentin",
            Age = 30
        };
        people.Add(quentin);

        List<Person> peopleThatStartWithW = new List<Person>();
        foreach (var person in people)
        {
            if (person.Name.StartsWith("W"))
            {
                peopleThatStartWithW.Add(person);
            }
        }

        foreach (var person in peopleThatStartWithW)
        {
            Console.WriteLine(person.Name);
        }

        Console.ReadLine();
    }
}

Here is some code that does the exact same thing but instead of using a loop to find Person objects with a Name that starts with W, it uses LINQ to grab all those Person objects in one line of code.

The LINQ Code:

//here is the Person class

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

//here is the Main method

class Program
{
    static void Main(string[] args)
    {
        List<Person> people = new List<Person>();
        Person dave = new Person()
        {
            Name = "Dave",
            Age = 28
        };
        people.Add(dave);
        Person arthur = new Person()
        {
            Name = "Arthur",
            Age = 31
        };
        people.Add(arthur);
        Person windell = new Person()
        {
            Name = "Windell",
            Age = 38
        };
        people.Add(windell);
        Person quentin = new Person()
        {
            Name = "Quentin",
            Age = 30
        };
        people.Add(quentin);

        //here is the new line of code

        List<Person> peopleThatStartWithW = people.Where(person => person.Name.StartsWith("W")).ToList();

        foreach (var person in peopleThatStartWithW)
        {
            Console.WriteLine(person.Name);
        }

        Console.ReadLine();
    }
}

So what is this crazy new => operator we’re using?

=> is the lambda operator

In this example we used the .Where() method to query the List<Person>. The lambda expression takes in one input parameter named person. Since we are calling the .Where() method on a List<Person> that input parameter will always be an object of type Person.

List<Person> peopleThatStartWithW = people.Where(person => person.Name.StartsWith("W")).ToList();

The right side of the expression is where the evaluation takes place. Just like in SQL, the expressions in the .Where() method must evaluate to true or false. So, the right side of our expression grabs the Name of each Person, and checks whether or not it begins with the letter W and then returns true or false based on that evaluation. When the result is true it saves the Person object and when it is false it ignores the Person object. Finally, we have all of the people that start with W in one List<Person>.

That’s just one way to use LINQ though, there are quite a few more.

Here are some useful links to LINQ stuff xD

Write a Comment

Comment