Saturday, June 12, 2021 20:50

Table of contents >> LINQ > Degenerate Select clauses

Degenerate Select clauses

Taking an excerpt code from the previous lessons about LINQ, we had these codes:


If you paid attention to the above code, you probably noticed the Select(n => n) function. If you analyze it a bit, you realize that it’s a lambda expression that all that it does is to take a parameter named n and return it, without any modification.

To prove that, I will create my own version of the Select() function:

See code changes


Legend:

  • green lines with a plus near the line numbers are newly added lines
  • red lines with a minus near the line numbers are removed lines


In this case, I had to slightly modify the signature of the Select() function as to be an IEnumerable<int> extension method, because the Where() function, which provides its numbers input, returns an IEnumerable<int> and not an int array.

If inside my Main() method I would have had something like Select(n => n + 5), that would have actually meant that I am taking n as a parameter and I am returning n + 5, effectively transforming n. But in our case, we have Select(n => n), which basically means “you’re an int, tranform into an int”. There is no transformation involved, which basically means we are wasting CPU time.

In the free form syntax of LINQ, we are forced to write it, though:

However, the compiler is smart enough to realize that this “hey, here is something, give it back, here is something, give it back” is utterly useless. And removes it, when it translates the query to normal MSIL code. Which means that we can actually remove it too, in the declarative syntax form:

See code changes


Legend:

  • green lines with a plus near the line numbers are newly added lines
  • red lines with a minus near the line numbers are removed lines



Of course, we can run the program and see that it produces the same output:

This kind of functions that are not really doing anything and are eliminated by the compiler are called degenerate clauses. And not only it is easier to write LINQ queries in the declarative syntax, but it is also shorter: one line of code, compared to three lines, in the case of the free form syntax. This is also the reason why most programmers prefer the declarative one, while the free form one is preferred mostly by those that come from a database development environment.

Tags: , ,

Leave a Reply



Follow the white rabbit