A List Consrehension is a type of notation set in which a programmer can describe the properties that members of a set must match. It is usually used to create a set based on other existing sets or sets by applying some type of combination, transformation, or reduction to existing sets.
Consider the following problem: you have a sequence of 10 numbers from 0 to 9, and you need to extract all the even numbers from this sequence. In a language such as C # version 1.1, you were pretty much limited to the following code to solve this problem:
ArrayList evens = new ArrayList(); ArrayList numbers = Range(10); int size = numbers.Count; int i = 0; while (i < size) { if (i % 2 == 0) { evens.Add(i); } i++; }
The code above does not show the implementation of the Range function, which is available in the full code list below. With the advent of C # 3.0 and the .NET Framework 3.5 in CY programming, Linq-based list notation is now available. The above C # 1.1 code can be ported to C # 3.0 as follows:
IEnumerable<int> numbers = Enumerable.Range(0, 10); var evens = from num in numbers where num % 2 == 0 select num;
And, from a technical point of view, the above C # 3.0 code can be written as single-line by moving the call to Enumarable. Go to the Linq expression that generates the evens sequence. In C # List Consrehension, I reduce the given numbers by applying a function (modulo 2) to this sequence. This creates a sequence of events in a much more concise manner and does not allow for the use of loop syntax. Now you may ask yourself: is this pure syntactic sugar? I donβt know, but I definitely research and maybe even ask the question myself. I suspect that this is not just syntactic sugar, but some true optimizations that can be done using basic monads.
A complete list of codes is available here .
Ξ» Jonas Gorauskas Jun 05 '09 at 3:00 2009-06-05 03:00
source share