LINQ - Overview: Example of A LINQ Query
LINQ - Overview: Example of A LINQ Query
Developers across the world have always encountered problems in querying data
because of the lack of a defined path and need to master a multiple of technologies
like SQL, Web Services, XQuery, etc.
class Program
{
static void Main()
{
string[] words = {"hello", "wonderful", "LINQ", "beautiful", "world"};
//Get only short words
var shortWords = from word in words
where word.Length <= 5
select word;
When the above code of C# is compiled and executed, it produces the following
result:
hello
LINQ
world
Syntax of LINQ
1
There are two syntaxes of LINQ. These are the following ones.
Example
var longWords = words.Where( w => w.length > 10);
Dim longWords = words.Where(Function(w) w.length > 10)
Example
var longwords = from w in words where w.length > 10;
Dim longwords = from w in words where w.length > 10
Types of LINQ
The types of LINQ are mentioned below in brief.
LINQ to Objects
LINQ to XML
LINQ to DataSet
LINQ to SQL
LINQ to Entities
Apart from the above, there is also a LINQ type named PLINQ which is Microsoft’s
parallel LINQ.
2
Query Expressions
Query expression is nothing but a LINQ query, expressed in a form similar to
that of SQL with query operators like Select, Where and OrderBy. Query expressions
usually start with the keyword “From”.
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Operators
{
3
class LINQQueryExpressions
{
static void Main()
{
// Specify the data source.
int[] scores = new int[] { 97, 92, 81, 60 };
When the above code is compiled and executed, it produces the following result:
97 92 81
Extension Methods
Introduced with .NET 3.5, Extension methods are declared in static classes only
and allow inclusion of custom methods to objects to perform some precise query
operations to extend a class without being an actual member of that class. These
can be overloaded also.
Stored procedures are much faster than a LINQ query as they follow an
expected execution plan.
It is easy to avoid run-time errors while executing a LINQ query than in
comparison to a stored procedure as the former has Visual Studio’s Intellisense
support as well as full-type checking during compile-time.
4
LINQ allows debugging by making use of .NET debugger which is not in case
of stored procedures.
LINQ offers support for multiple databases in contrast to stored procedures,
where it is essential to re-write the code for diverse types of databases.
Deployment of LINQ based solution is easy and simple in comparison to
deployment of a set of stored procedures.
Below is an example of how many diverse techniques were used by the developers
while querying a data before the advent of LINQ.
SqlConnection sqlConnection = new SqlConnection(connectString);
SqlConnection.Open();
System.Data.SqlClient.SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "Select * from Customer";
return sqlCommand.ExecuteReader (CommandBehavior.CloseConnection)
Interestingly, out of the featured code lines, query gets defined only by the last two.
Using LINQ, the same data query can be written in a readable color-coded form like
the following one mentioned below that too in a very less time.
Northwind db = new Northwind(@"C:\Data\Northwnd.mdf");
var query = from c in db.Customers
select c;
Advantages of LINQ
LINQ offers a host of advantages and among them the foremost is its powerful
expressiveness which enables developers to express declaratively. Some of the other
advantages of LINQ are given below.
LINQ offers syntax highlighting that proves helpful to find out mistakes during
design time.
LINQ offers IntelliSense which means writing more accurate queries easily.
Writing codes is quite faster in LINQ and thus development time also gets
reduced significantly.
LINQ makes easy debugging due to its integration in the C# language.
5
Viewing relationship between two tables is easy with LINQ due to its
hierarchical feature and this enables composing queries joining multiple
tables in less time.
LINQ allows usage of a single LINQ syntax while querying many diverse
data sources and this is mainly because of its unitive foundation.
LINQ is extensible that means it is possible to use knowledge of LINQ to
querying new data source types.
LINQ offers the facility of joining several data sources in a single query as
well as breaking complex problems into a set of short queries easy to
debug.
LINQ offers easy transformation for conversion of one data type to
another like transforming SQL data to XML data.
LINQ standard query operators can be categorized into the following ones on the
basis of their functionality.
Filtering Operators
Join Operators
Projection Operations
Sorting Operators
Grouping Operators
Conversions
Concatenation
Aggregation
Quantifier Operations
Partition Operations
Generation Operations
Set Operations
Equality
Element Operators
6
Filtering Operators
Filtering is an operation to restrict the result set such that it has only selected elements
satisfying a particular condition.
VB Query
Operator Description C# Query Expression Syntax Expression
Syntax
Join Operators
Joining refers to an operation in which data sources with difficult to follow
relationships with each other in a direct way are targeted.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Operators
{
class Program
7
foreach (string str in query)
Console.WriteLine(str);
Console.ReadLine();
VB Query
Operator Description C# Query Expression Syntax Expression
Syntax
From x In
The operator join two sequences on basis of …, y In …
Join join … in … on … equals …
matching keys Where x.a
= y.a
Group Join
Join two sequences and group the matching join … in … on … equals … into
GroupJoin … In … On
elements …
…
Projection Operations
Projection is an operation in which an object is transformed into an altogether new
form with only specific properties.
C# Query VB Query
Operator Description Expression Expression
Syntax Syntax
Use
The operator project the sequences of values which are
Use multiple multiple
SelectMany based on a transform function as well as flattens them into a
from clauses From
single sequence
clauses
Sorting Operators
8
A sorting operation allows ordering the elements of a sequence on basis of a single or
more attributes.
VB Query
C# Query Expression
Operator Description Expression
Syntax
Syntax
Order By ...
OrderByDescending The operator sort values in a descending order orderby ... descending
Descending
Order By
Executes a secondary sorting in a descending orderby …, …
ThenByDescending …, …
order descending
Descending
Grouping Operators
The operators put data into some groups based on a common shared attribute.
VB Query
C# Query Expression
Operator Description Expression
Syntax
Syntax
Conversions
The operators change the type of input objects and are used in a diverse range of
applications.
Show Examples
9
VB Query
C# Query Expression
Operator Description Expression
Syntax
Syntax
Not
AsEnumerable Returns the input typed as IEnumerable<T> Not Applicable
Applicable
Concatenation
Performs concatenation of two sequences and is quite similar to the Union operator in
terms of its operation except of the fact that this does not remove duplicates.
VB Query
C# Query Expression
Operator Description Expression
Syntax
Syntax
Aggregation
10
Performs any type of desired aggregation and allows creating custom aggregations in
LINQ.
Show Examples
VB Query
Operator Description C# Query Expression Syntax Expression
Syntax
Aggregate
Average value of a collection of values is … In …
Average Not Applicable
calculated Into
Average
Aggregate
Counts the elements satisfying a predicate
Count Not Applicable … In …
function within collection
Into Count
Aggregate
Counts the elements satisfying a predicate … In …
LonCount Not Applicable
function within a huge collection Into
LongCount
Aggregate
Find out the maximum value within a
Max Not Applicable … In …
collection
Into Max
Aggregate
Find out the minimum value existing within a
Min Not Applicable … In …
collection
Into Min
Aggregate
Find out the sum of a values within a
Sum Not Applicable … In …
collection
Into Sum
Quantifier Operations
These operators return a Boolean value i.e. True or False when some or all elements
within a sequence satisfy a specific condition.
11
VB Query
C# Query Expression
Operator Description Expression
Syntax
Syntax
Aggregate
Returns a value ‘True’ if all elements of a sequence … In …
All Not Applicable
satisfy a predicate condition Into
All……
Aggregate
Determines by searching a sequence that whether any
Any Not Applicable … In …
element of the same satisfy a specified condition
Into Any
Partition Operators
Divide an input sequence into two separate sections without rearranging the elements
of the sequence and then returning one of them.
C# Query VB Query
Operator Description Expression Expression
Syntax Syntax
Generation Operations
A new sequence of values is created by generational operators.
12
VB Query
Operator Description C# Query Expression Syntax Expression
Syntax
Set Operations
There are four operators for the set operations, each yielding a result based on
different criteria.
C# Query VB Query
Operator Description Expression Expression
Syntax Syntax
Compares the values of two collections and return the ones Not
Except Not Applicable
from one collection who are not in the other collection Applicable
Equality
Compares two sentences enumerableenumerable and determine are they an exact match
or not.
13
VB Query
Operator Description C# Query Expression Syntax Expression
Syntax
Element Operators
Except the DefaultIfEmpty, all the rest eight standard query element operators return a
single element from a collection.
C# Query VB Query
Operator Description Expression Expression
Syntax Syntax
14
Same as Single except that it also returns a default
Not
SingleOrDefault value if there is no existence of any such lone Not Applicable
Applicable
element
15
A Dataset offers an extremely useful data representation in memory and is used for a
diverse range of data based applications. LINQ to Dataset as one of the technology of
LINQ to ADO.NET faciliatates performing queries on the data of a Dataset in a
hassle-free manner and enhance productivity.
LINQ - Objects
LINQ to Objects offers usage of any LINQ query supporting IEnumerable<T>for
accessing in-memory data collections without any need of LINQ provider APIAPI as
in case of LINQ to SQL or LINQ to XML.
There are also many advantages of LINQ to Objects over traditional foreach loops
like more readability, powerful filtering, capability of grouping, enhanced ordering
with minimal application coding. Such LINQ queries are also more compact in nature
and are portable to any other data sources without any modification or with just a little
modification.
namespace LINQtoObjects
{
class Program
{
static void Main(string[] args)
{
string[] tools = { "Tablesaw", "Bandsaw", "Planer", "Jointer",
"Drill",
"Sander" };
var list = from t in tools
select t;
16
foreach (string s in list)
{
sb.Append(s + Environment.NewLine);
}
Console.WriteLine(sb.ToString(), "Tools");
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Tablesaw
Bandsaw
Planer
Jointer
Drill
Sander
namespace LINQtoObjects
{
class Department
{
public int DepartmentId { get; set; }
public string Name { get; set; }
}
class LinqToObjects
{
static void Main(string[] args)
{
List<Department> departments = new List<Department>();
departments.Add(new Department { DepartmentId = 1, Name = "Account"
});
departments.Add(new Department { DepartmentId = 2, Name = "Sales" });
departments.Add(new Department { DepartmentId = 3, Name = "Marketing"
});
17
var departmentList = from d in departments
select d;
When the above code of C# is compiled and executed, it produces the following
result:
Department Id = 1, Department Name = Account
Department Id = 2, Department Name = Sales
Department Id = 3, Department Name = Marketing
Below is a simple example of a LINQ to Dataset query in which a data source is first
obtained and then the dataset is filled with two data tables. A relationship is
established between both the tables and a LINQ query is created against both tables by
the means of join clause. Finally, foreach loop is used to display the desired results.
C#
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LINQtoDataset
{
18
class Program
{
static void Main(string[] args)
{
string connectString =
System.Configuration.ConfigurationManager.ConnectionStrings["LinqToSQLDBConne
ctionString"].ToString();
DataRelation dr = ds.Relations.Add("FK_Employee_Department",
ds.Tables["Department"].Columns["DepartmentId"],
ds.Tables["Employee"].Columns["DepartmentId"]);
19
LINQ - XML
LINQ to XML offers easy accessibility to all LINQ functionalities like standard query
operators, programming interface, etc. Integrated in the .NET framework, LINQ to
XML also makes the best use of .NET framework functionalities like debugging,
compile-time checking, strong typing and many more to say.
LINQ to XML has its power in the System.Xml.Linq namespace. This has all the 19
necessary classes to work with XML. These classes are the following ones.
XAttribute
XCData
XComment
XContainer
XDeclaration
XDocument
XDocumentType
XElement
XName
XNamespace
XNode
XNodeDocumentOrderComparer
XNodeEqualityComparer
XObject
XObjectChange
XObjectChangeEventArgs
XObjectEventHandler
XProcessingInstruction
XText
20
Read the XML File using LINQ
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace LINQtoXML
{
class ExampleOfXML
{
static void Main(string[] args)
{
string myXML = @"<Departments>
<Department>Account</Department>
<Department>Sales</Department>
<Department>Pre-Sales</Department>
<Department>Marketing</Department>
</Departments>";
namespace LINQtoXML
{
class ExampleOfXML
{
static void Main(string[] args)
{
21
string myXML = @"<Departments>
<Department>Account</Department>
<Department>Sales</Department>
<Department>Pre-Sales</Department>
<Department>Marketing</Department>
</Departments>";
namespace LINQtoXML
{
22
class ExampleOfXML
{
static void Main(string[] args)
{
string myXML = @"<Departments>
<Department>Support</Department>
<Department>Account</Department>
<Department>Sales</Department>
<Department>Pre-Sales</Department>
<Department>Marketing</Department>
<Department>Finance</Department>
</Departments>";
When the above code of C# is compiled and executed, it produces the following
result:
Department Name - Support
Department Name - Account
Department Name - Pre-Sales
Department Name - Marketing
Department Name - Finance
LINQ - Entities
A part of the ADO.NET Entity Framework, LINQ to Entities is more flexible than
LINQ to SQL, but is not much popular because of its complexity and lack of key
features. However, it does not have the limitations of LINQ to SQL that allows data
query only in SQL server database as LINQ to Entities facilitates data query in a large
number of data providers like Oracle, MySQL, etc.
23
Moreover, it has got a major support from ASP.Net in the sense that users can make
use of a data source control for executing a query via LINQ to Entities and facilitates
binding of the results without any need of extra coding.
LINQ to Entities has for these advantages become the standard mechanism for the
usage of LINQ on databases nowadays. It is also possible with LINQ to Entities to
change queried data details and committing a batch update easily. What is the most
intriguing fact about LINQ to Entities is that it has same syntax like that of SQL and
even has the same group of standard query operators like Join, Select, OrderBy, etc.
ObjectContext is here the primary class that enables interaction with Entity Data
Model or in other words acts as a bridge that connects LINQ to the database.
Command trees are here query representation with compatibility with the Entity
framework. The Entity Framework on the other hand is actually Object Relational
Mapper abbreviated generally as ORM by the developers that does the generation of
business objects as well as entities as per the database tables and facilitates various
basic operations like create, update, delete and read.
24
Example of ADD, UPDATE and DELETE using LINQ with
Entity Model
First add Entity Model by following below steps.
Step 1: Right click on project and click add new item will open window as per
below. Select ADO.NET Entity Data Model and specify name and click on
Add.
25
Step 2: Select Generate from database.
26
Step 3: Choose Databse Connection.
27
Step 4: Select all the tables.
28
Now write the following code.
using DataAccess;
using System;
using System.Linq;
namespace LINQTOSQLConsoleApp
{
public class LinqToEntityModel
{
static void Main(string[] args)
{
using (LinqToSQLDBEntities context = new LinqToSQLDBEntities())
{
//Get the List of Departments from Database
var departmentList = from d in context.Departments
select d;
29
foreach (var dept in departmentList)
{
Console.WriteLine("Department Id = {0} , Department Name =
{1}",
dept.DepartmentId, dept.Name);
}
context.Departments.Add(department);
context.SaveChanges();
When the above code is compiled and executed, it produces the following result:
30
LINQ - Lambda Expressions
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.
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.
C#
using System;
31
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lambdaexample
{
class Program
{
delegate int del(int i);
static void Main(string[] args)
{
del myDelegate = y => y * y;
int j = myDelegate(5);
Console.WriteLine(j);
Console.ReadLine();
}
}
}
When the above code of C# is compiled and executed, it produces the following
result:
25
Expression Lambda
As the expression in the syntax of lambda expression shown above is on the right
hand side, these are also known as expression lambda.
Async Lambdas
The lambda expression created by incorporating asynchronous processing by the use
of async keyword is known as async lambdas. Below is an example of async lambda.
Func<Task<string>> getWordAsync = async() => “hello”;
C#
32
//Get the average of the odd Fibonacci numbers in the series...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lambdaexample
{
class Program
{
static void Main(string[] args)
{
int[] fibNum = { 1, 1, 2, 3, 5, 8, 13, 21, 34 };
double averageValue = fibNum.Where(num => num % 2 == 1).Average();
Console.WriteLine(averageValue);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
7.33333333333333
Here the compiler employ the type inference to draw upon the fact that x is an integer
and this is done by examining the parameter type of the Transformer.
33
Here is an example to demonstrate variable scope in lambda expression.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lambdaexample
{
class Program
{
delegate bool D();
delegate bool D2(int i);
class Test
{
D del;
D2 del2;
public void TestMethod(int input)
{
int j = 0;
// Initialize the delegates with lambda expressions.
// Note access to 2 outer variables.
// del will be invoked within this method.
del = () => { j = 10; return j > input; };
// Demonstrate value of j:
// The delegate has not been invoked yet.
Console.WriteLine("j = {0}", j); // Invoke the delegate.
bool boolResult = del();
Console.WriteLine(result);
Console.ReadKey();
}
}
}
}
When the above code is compiled and executed, it produces the following result:
34
j = 0
j = 10. b = True
True
Expression Tree
Lambda expressions are used in Expression Tree construction extensively. An
expression tree give away code in a data structure resembling a tree in which every
node is itself an expression like a method call or can be a binary operation like x<y.
Below is an example of usage of lambda expression for constructing an expression
tree.
Statement Lambda
There is also statement lambdas consisting of two or three statements, but are not
used in construction of expression trees. A return statement must be written in a
statement lambda.
namespace lambdaexample
{
class Program
{
static void Main(string[] args)
{
int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };
35
}
}
}
When the above code is compiled and executed, it produces the following result:
3
8
1
7
9
2
8
Lambdas are employed as arguments in LINQ queries based on methods and never
allowed to have a place on the left side of operators like is or as just like anonymous
methods. Although, Lambda expressions are much alike anonymous methods, these
are not at all restricted to be used as delegates only.
https://www.tutorialspoint.com/linq/linq_overview.htm
Copyright © tutorialspoint.com
36