LINQ (Language-Integrated Query)
LINQ makes a query
a first-class language construct. You write queries against strongly
typed collections of objects. The actual execution of the query is
deferred until you iterate over the query variable
(e.g., by using foreach,
.ToArray() or .Count(). This concept is referred to as
deferred execution. Remember this to avoid processing a collection of items more than once.
LINQ methods
include many of the common SQL database methods, like, Where, Select,
Join, Union, Distinct, GroupBy, Average, Sum, Min, Max, Count, All, Any,
Contains, and more.
LINQ may be expressed either in
comprehension syntax or as calls to extension methods.
Comprehension Syntax
IEnumerable<int> numQuery =
from num in numbers
where (num % 2) == 0
select num;
Extension Method with Lambda Expression
IEnumerable<int> numQuery = numbers.Where(num => (num % 2) == 0);
Lambda Expressions
By using
lambda expressions, you can write local functions that can be passed as
arguments or returned as the value of function calls.
For example, the lambda expression
c => c.City == "London"
is the same as
delegate (Customer c)
{
return c.City == "London";
}
{
return c.City == "London";
}
Lambda expressions are particularly helpful for writing LINQ query expressions.
Functional Programming
LINQ technology is a form of declarative, functional programming.
Functional programming is a form of
declarative programming. Mainstream languages, such as C#, C++, and Java, were designed to primarily support
imperative (procedural) programming. With an imperative approach,
a developer writes code that describes in exacting detail the steps
that the computer must take to accomplish the goal. This is sometimes
referred to as
algorithmic programming. In contrast, a functional approach
involves composing the problem as a set of functions to be executed. You
define carefully the input to each function, and what each function
returns.
The following table describes some of the general differences between these two approaches.
Characteristic
|
Imperative approach
|
Functional approach
|
Programmer focus
|
How to perform tasks (algorithms)
|
What information is desired and what transformations are required
|
Order of execution
|
Important
|
Low importance
|
Primary flow control
|
Loops, conditionals, and function (method) calls
|
Function calls, including recursion
|
Primary manipulation unit
|
Instances of structures or classes
|
Functions as first-class objects and data collections
|
BTW, F# is a functional language.
No comments:
Post a Comment