Pages

Saturday, June 2, 2012

C# LINQ



Imperative code describes how to complete an algorithm step-by-step. Declarative code instead describes the end result of that algorithm. LINQ is a declarative syntax form that was introduced into the C# language. It makes some computational tasks easier.
We call this language the query language, because it is very useful for retrieving information from data bases by formulating queries, or questions, expressed in the language.
Abelson & Sussman, p. 440

System.Linq

.NET Framework information
LINQ—language integrated query—introduces many different extensions methods to your standard C# environment. For example, you can use the Average extension method to average all the elements in a collection. It works on Lists, arrays and collections that are not yet in memory.
Program that uses LINQ extension [C#]
sing System;
uusing System.Linq;
lass Program
c{
static void Main()
{
] array = { 1, 3, 5, 7 }; Con
int [sole.WriteLine(array.Average());
} }
Output
4

Conversion

Conversion or change
These extension methods perform a conversion from an IEnumerable collection into a certain collection: an array, Dictionary, List or Lookup data structure. We describe the methods, which are some of the most useful in the System.Linq namespace.
ToArrayToDictionaryToListToLookup

Mutation

These methods filter or mutate one or more collections. In other words, these will change the elements in your query in some way: by removing unneeded elements, by adding new elements, or by changing other aspects of the elements themselves.
Select method callAsEnumerableAsParallelCastConcatDefaultIfEmptyDistinctElementAtElementAtOrDefaultExceptFirstFirstOrDefaultGroupByGroupJoinIntersectLastLastOrDefaultOfTypeOrderByOrderByDescendingReverseSelectSelectManySingleSingleOrDefaultUnionWhereZipSkip illustration
Skip and Take methods. The Skip and Take extension methods are particularly useful. They eliminate the need for you to compose custom code to check ranges. They are recommended in a variety of contexts in your C# programs.
SkipSkipWhileTakeTakeWhile

Computation

Another function that LINQ provides is computational methods: these act upon a certain query and then return a number or other value. These can also simplify your code, by eliminating the requirement of computing values such as averages yourself.
Any methodAggregateAllAnyAverageCountSequenceEqualSum
Max and Min. You can search a collection for its largest (max) or smallest (min) value. This is effective for many value types, such as strings and numbers.
MaxMin

Enumerable

The Enumerable type presents some static methods that can be useful in certain situations, as we reveal in these examples.
EmptyRangeRepeat

Query

Find icon
Next, let's explore query expressions in the C# language. Query expressions are built with declarative clauses that specify the results you want, not how you want to achieve them. Let's check out this program that uses a query expression on an in-memory array of integers.
Imperative:
You describe how to accomplish the task by indicating each step in code.

Declarative:
You describe the final result needed, leaving the steps up to the query language.

Program that uses query expression [C#]
sing System;
uusing System.Linq;
lass Program
c{
static void Main()
{
] array = { 1, 2, 3, 6, 7, 8 };
int
[// Query expression.
var elements = from element in array
orderby element descending
select element;
where element > 2
// Enumerate.
foreach (var element in elements)
{ Console.Write(element);
sole.WriteLine(); }
Console.Write(' '); } Co n}
Output
7 6 3
8
Description. In the query expression, we select all the elements from the array in descending order (high to low). We then filter out elements less than or equal to 2. In the foreach-loop, we evaluate the expression and print the results.

Query keywords

Let contextual keyword
Query expressions use a whole new set of keywords. These are contextual keywords. This means they only have meaning in query expressions. These query clauses are described in more detail.
ascendingdescendinggroupjoinletorderbyselect new

Summary

The C# programming language
Though they typically reduce performance, LINQ methods and query expressions often improve the readability of C# programs. LINQ sometimes leads to new algorithmic approaches. And with lazy evaluation, we delay expensive operations. This yields more immediate results.

No comments:

Post a Comment