UNDERSTANDING LIST COMPREHENSIONS

The notion of lists is deeply embedded in many programming languages. This is quite natural because computers are good at repetitive tasks. A lot of algorithms evolve around executing certain calculations, in the widest possible sense of the word, over lists of data.

In imperative languages, the importance of lists usually leads to the inclusion of array features in the language syntax, while more complex as well as flexible list types are typically implemented in libraries.

Initialization syntax support that works with many different lists was added to C# in version 3.0. Unfortunately, this support isn’t very clean because the language uses an arbitrary mechanism to find out whether this syntax is supported for a given type, and to actually add the elements. For instance, the type has to implement the interface IEnumerable and it needs to have an Add method. IEnumerable isn’t needed at all for the purpose of adding elements to the collection, and Add is a member of a different interface in most of the standard .NET collections. On the other hand, even if a class has a constructor that takes an IEnumerable as a parameter, it is not used by the mechanism, resulting in potential performance drawbacks.

image

The initialization syntax for array types has been available in C# since version 1.0, and it works differently. The mechanism outlined here is the ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.