LINQ Study Note – 02

Three Actions

In LINQ, we always work with objects, instead of the data source. Therefore, in the LINQ pattern, we always have three actions.

  • Obtain the data source
  • Create the query
  • Execute the query

Regarding the data source, the data source LINQ work with should support generic IEnumerable<T> interface; In other words, LINQ serves as extension class methods for IEnumerable<T>. In Microsoft’s document, these types are referred to as queryable type.

Method Syntax and Query Syntax

In LINQ, there are two kinds of syntax in C# programming language. There are pros and cons; we can choose anyone depends on the circumstance or our preference.

Method Syntax is implemented using dot syntax, which is short and clean; whereas Query Syntax looks like plain language that we use daily. I personally prefer Query Syntax.


Example

We have a Employee class in our project, and it has two properties, name and id. We also have a List property named developers, which holds two Employee objects.

public class Employee
     {
         public int Id { get; set; }
         public string Name { get; set; }
     }

In our program.cs file, we initialise a List named developers.

IEnumerable developers = new Employee[]
{
    new Employee { Id = 1, Name = "Scott"},
    new Employee { Id = 2, Name = "Chris"}
             };

Now, we will fetch objects in developers List, and we want to filter out any objects whose name’s length is equal to 5.

Method Syntax

var methodSyntax = developers.Where(e => e.Name.Lengh == 5)
                                  .OrderBy(e => e.Name);

Query Syntax

var querySyntax = from developer in developers
                  where developer.Name.Length == 5
                  Orderby developer.Name
                  select developer;

As we can see, Query Syntax is similar with our daily plain language and a bit easy to pick up.


Deferred Execution

In the above code snippet, we have a Method Syntax query and a Query Syntax query. Both of them don’t take action or return data. They just store the information that is required to produce the result when the query is executed at some later point.

In another word, the actual execution is deferred until we loop through the query variable.

foreach (var employee in querySyntax)
{
    Console.WriteLine(employee.Name);
}

Force Immediate Execution

Some query method doesn’t need to execute the foreach loop when it is called; actually, they may have a build-in foreach loop behind the scene. For example, Count(). We don’t need to run a foreach loop when we run the Count() function. This is called Immediate Execution.

querySyntax.Count();

We also can cache a query’s immediate execution result into a collection with ToList() or ToArray() method.

querySyntax.ToList();
querySyntax.ToArray();

Leave a Reply

Your email address will not be published. Required fields are marked *