VISUAL PROGRAMMING
CSC444/CSC412
Lecture – 18&19
1
Topics to Cover
• What is LINQ
• Why should we use LINQ and what are the benefits of using LINQ
• LINQ Architecture
• LINQ Providers
• Examples
2
What is LINQ
• LINQ stands for Language Integrated Query. LINQ enables us to query
any type of data store (SQL Server, XML documents, Objects in
memory etc).
3
Why should we use LINQ and what are the
benefits of using LINQ
If the .NET application that is being developed
a) Requires data from SQL Server - Then the developer
has to understand ADO.NET code and SQL specific to
SQL Server Database
b) Requires data from an XML document - Then the
developer has to understand XSLT & XPATH queries
c) Need to query objects in memory (List<Customer>,
List<Order> etc) - Then the developer has to understand
how to work with objects in memory
4
Why should we use LINQ and what are the
benefits of using LINQ
• LINQ enables us to work with these different data sources using a
similar coding style without having the need to know the syntax
specific to the data source.
• Another benefit of using LINQ is that it provides intellisense and
compile time error checking.
5
LINQ Architecture & LINQ Providers
1. LINQ query can be written using any .NET supported programming language
2. LINQ provider is a component between the LINQ query and the actual data source, which
converts the LINQ query into a format that the underlying data source can understand. For example
LINQ to SQL provider converts a LINQ query to T-SQL that SQL Server database can understand.
6
LINQ Architecture & LINQ Providers
• If we misspell table or column names in the SQL Query, we will not
know about it at compile time. At run time the page crashes and
that's when we will know about this error. Also notice that there is
no intellisense when typing table and column names.
• Misspelled column names when reading from the reader will also
cause the same problem. With LINQ we will have intellisense and
compile time error checking. With LINQ we get intellisense. If we
misspell the table or column names we will get to know about them
at compile time.
7
Three Parts of a Query Operation
• All LINQ query operations consist of three distinct actions:
• Obtain the data source.
• Create the query.
• Execute the query.
8
String Array Example:
string combineString = "";
string[] words = { "hello", "wonderful", "LINQ", "beautiful", "world" };
var shortWords = from word in words where word.Length <= 5 select word;
foreach (string q in shortWords)
{
combineString = combineString + q + " ";
}
// combineString = string.Join(" ", shortWords);
textBox2.Text = combineString;
Example:
10
Description
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
var numQuery =
from num in numbers
where (num % 2) == 0
select num;
• num is the range variable:
• The range variable is like the iteration variable in a foreach loop except that no actual iteration
occurs in a query expression.
11
Description
• Our first LINQ query begins with a From clause which specifies a
range variable (value) and the data source to query (the array
values).
• The range variable represents each item in the data source, much like
the control variable in a Foreach statement.
• If the condition in the Where clause evaluates to True, the element is
selected—that is, it’s included in the collection of Integers that
represents the query results.
• Here, the Integers in the array are included only if they’re even.
Description
• For each item in the data source, the Select clause determines what value
appears in the results.
• In this case, it’s the Integer that the range variable currently represents.
• The Select clause is usually placed at the end of the query for clarity,
though it may be placed after the From clause and before other clauses,
or omitted.
• If omitted, the range variable is implicitly selected.
• The Select clause can transform the selected items—for example,
Select value * 2 in this example would have multiplied each selected
value in the result by 2.
Deferred Execution and Transforming Query
Results
• LINQ uses a technique called deferred execution—a query executes
only when you iterate over the results, not when the query is defined.
• This allows you to create a query once and execute it many times.
• If you make any changes to the data in a LINQ query’s data source,
the next time you iterate over the query’s results, the query will
process the current data in the data source.
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
Deferred Execution and Transforming Query
Results
• The following example shows the order of execution when using
an extension method that uses deferred execution. The example
declares an array of three strings. It then iterates through the
collection returned by ConvertCollectionToUpperCase.
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
public static class LocalExtensions
{
public static IEnumerable<string>
ConvertCollectionToUpperCase(this
IEnumerable<string> source)
{
foreach (string str in source)
{
Console.WriteLine("ToUpper: source {0}", str);
yield return str.ToUpper();
}
}
}
class Program {
static void Main(string[] args)
{
string[] stringArray = { "abc", "def", "ghi" };
var q = from str in
stringArray.ConvertCollectionToUpperCase() select str;
foreach (string str in q)
Console.WriteLine("Main:
© 1992-2011 by Pearsonstr {0}",Inc.str);
Education, } }Reserved.
All Rights
Output:
ToUpper: source abc
Main: str ABC
ToUpper: source def
Main: str DEF
ToUpper: source ghi
Main: str GHI
© 1992-2011 by Pearson Education, Inc. All Rights Reserved.
LINQ Operaters
• Filtering (Where)
• Grouping (Group By)
• Concatenation (Concat)
• Sorting (OrderBy, OrderByDescending)
• Join operator (Join)
18
Sorting Elements Using LINQ
• The Order By clause sorts the query results in ascending order.
• You can use the Descending modifier in the Order By clause to sort query
results in descending order.
• An Ascending modifier also exists but is rarely used, because it’s the default.
• You can use the Order By clause only for values that can be compared to one
another.
• The Order By clause supports values of any type that implements the interface
IComparable, such as the primitive numeric types and String.
20
Write LINQ queries
• There are 2 ways to write LINQ queries using these Standard Query
Operators
• 1. Using SQL like query expressions
• 2. Using Lambda Expressions.
21
Lambda in Standard Query Operators
• The term ‘Lambda expression’ has derived its name from ‘lambda’ calculus which in turn is a
mathematical notation applied for defining functions.
• Lambda expressions as a LINQ equation’s executable part translate logic in a way at run time
so it can pass on to the data source conveniently.
• However, lambda expressions are not just limited to find application in LINQ only.
• These expressions are expressed by the following syntax −
(input-parameters) => expression
• Here is an example of a lambda expression −
y⇒y*y
• The above expression specifies a parameter named y and that value of y is squared.
However, it is not possible to execute a lambda expression in this form. Example of a lambda
expression in C# is shown below.
22
Using Lambda Expression
23
Example:
int[] numbers = { 2, 3, 4, 5 };
var squaredNumbers = numbers.Select(x => x * x);
Console.WriteLine(string.Join(" ", squaredNumbers));
// Output: // 4 9 16 25
Var sqr=from n in numbers select n*n
24
Using Lambda Expression
• A lambda expression within a query operator is evaluated by the
same upon demand and continually works on each of the
elements in the input sequence and not the whole sequence.
Developers are allowed by Lambda expression to feed their
own logic into the standard query operators. In the below
example, the developer has used the ‘Where’ operator to
reclaim the odd values from given list by making use of a
lambda expression.
25
Example:
26