Description
LINQ means "Language Integrated Query". LINQ is a new feature which is used to query the data. By using LINQ, one can query any type of data like XML, Relational, and Objects.
Generally, In Object Oriented Programming, Everything that deal with the class as well as the object. As a programmer, it is compulsory to learn different kinds of Query Languages. Query Languages will differ from database to database as shown in the below figure.
Description
LINQ is a Data Access Technology like ADO.Net. But Why should one use LINQ?
The answer for this question is "To avoid the Impedance Mismatch". Impedance Mismatch means the gap between the database and the objects as shown in the above figure.
Here, we need OR Mapping Tools to fill the gap between Object Oriented Programming(C#.Net) and database.
See the below figure, to get an idea.
Types
There are different types of OR Mapping Tools such as
- LINQ
- Hibernate
- NHibernate
let's concentrate on LINQ only. LINQ was introduced in
.Net framework 3.0 but, the complete implementations with all the features came in the .
Net Framework3.5.
Advantages
The below are some of the advantages of LINQ.
- Programmer burden will decrease.
- No need to learn different Query Languages.
- Rapid Application Development(RAD) facilities are provided.
- Execution of the queries will be fastest. Because Queries are executed in the front end application only.
- Built in Security will be provided.
Types
There are two types of data types in LINQ
- Named Types
- Anonymous Types
Description
Named Types are built-in types or user-defined types. In Named types, the user will decide the type of the variable.
Example
int a=10;
double b=20.5;
String s="john";
Description
Anonymous Types are Class Types. That means Anonymous Types are generated by the compiler. i.e, compiler will decide the type of the variable.
One have to declare Anonymous Type variable using Var keyword as shown in below Example.
Example
Var a=10;
Var b=20.5;
var s="john";
Limitations of Anonymous Types
Limitation 1
Anonymous Types can not be used as data fields. Anonymous Types can be used as local variables only.
Example
[csharp]
class c1
{
var a = 10; //Not Allowed, Raises Compile time error
public void f1()
{
var a = 10;//Allowed
}
}
[/csharp]
Limitation 2
An Anonymous Typed Variable should be initialized.
Example
[csharp]
var a; //Wrong
var a=10; // Right
[/csharp]
Limitation 3
To initialize multiple variables, we cannot use a single statement rather we can create multiple statements like.
Example
[csharp]
var a=10,b=20.9,c=40; //Not allowed, Raises compiler error
var a=10; //Allowed
var b=20.9; //Allowed
var c=40; //Allowed
[/csharp]
Description
One can use Anonymous Types in 4 areas.
They are
- As a local variable
- In for loop initialization
- In for each loop initialization
- In blocks or statements
one can also create
complex types using Anonymous Types.
Example
[csharp]
var Name=new{Name="john",
FatherName="James",
LastName="George"};
[/csharp]
This is the example for complex types. Such kind of complex types is created by using New keyword with an initializer.
Categories in Anonymous Types
Types
Anonymous Types are divided as shown in the below figure.
Difference between Named Types and Anonymous Types
Table
Named Types |
Anonymous Types |
Type is know at source time. |
Type is know at compile time. |
User/programmer will decide the type of the variable. |
Complier will decide the type of the variable. |
Respective type of keyword is used to create Named Type variable. |
Var Keyword is used to create Anonymous Type variable. |
Named Type Variable can be used as Local/Global Variable |
Anonymous Type Variable can be used as Local Variable only. |
Named Type Variable can be used in any context |
Anonymous Type Variable can be used in the following contexts only.
- As local variable
- in statements
- in for loop and for each loop initialization
|
Initialization of variable is optional. |
initialization of variable is mandatory. |
Suppoert Unary Operators(increment/decrement)like a=a++ |
Does not support Unary Operations(increment/decrement)like a=a++ |
One can declare multiple variables in same statement. |
One cannot declare multiple variables in same statement. |
Primitive Types do not support complex types. |
Support complex types. |
Example for Anonymous Types
Example 1
[csharp]
static void main()
{
var a = 10;
var b = 30.6;
var s = "John";
Console.WriteLine("value of a is" + a);
Console.WriteLine("value of b is" + b);
Console.WriteLine("value of c is" + s);
Console.ReadLine();
}
[/csharp]
Example 2
[csharp]
static void main()
{
string[] Names = { "John", "Devid", "James" };
Console.WriteLine("List Of Names are:");
foreach(var x in Names)
{
Console.WriteLine(x + "");
}
Console.ReadLine();
}
[/csharp]
Example 3
[csharp]
static void main()
{
var Names =new { FirstName="John",SecondName="Devid", ThirdName="James" };
Console.WriteLine("Names are:"+Names.FirstName+Names.SecondName+Names.ThirdName);
Console.ReadLine();
}
[/csharp]
These are the some of the examples for Anonymous Types.
Description
Anonymous Function is introduced in
.Net Framework 2.0. An Anonymous Function is a function which is similar to standard functions. Anonymous Functions also take the inputs and gives the outputs. The only difference between the standard functions and the Anonymous Function is
Name.
An Anonymous Function does not contain a name. The Anonymous Function only contains the implementation.
In general,
Anonymous Functions are used within Delegates or Lambda Expressions.
Example
[csharp]
namespace AnonymousFunctionExample
{
class Example
{
delegate void sampledelegate(string s);//Anonymous Function with in the delegate
static void main()
{
sampledelegate obj=delegate(string s)
{
Console.WriteLine("Value is:"+s);
};
obj("James");
Console.ReadLine();
}
}
}
[/csharp]
See the above example. Above example shows the Anonymous Function with in the delegate.
Description
A Lambda Expression is an anonymous function or method which returns a value. Lambda Expression derived from a mathematical term 'Lambda'. Lambda Expression decrease the burden on the programmer. By using Lambda Expression, one can write an anonymous function without a delegate.
Syntax
Arguments=>Body of the Function or Expression.
Here,'=>' indicates the Lambda Expression.
Example
X=>X*X
The above Expression implies that X goes to X*X
Here, the first value i.e X means the arguments in the function and the second value i.e X*X means the Expression.
Difference between An Anonymous function and a Lambda Expression
Description
See the below examples to know the difference between An anonymous function and a lambda expression.
Example 1
[csharp]
//An anonymous function
delegate int mul(int i);
mul obj= delegate(int value)
{
return (value*2);
};
int i = obj(10);
[/csharp]
Example 2
[csharp] //Lambda Expression
<span class="code-keyword">delegate</span>
<span class="code-keyword">int mul</span>
<span class="code-keyword">int(i) mul obj</span>
<span class="code-keyword">value=></span>
<span class="code-keyword">value*</span>
<span class="code-digit">2</span>
<span class="code-keyword">int i = obj</span>
<span class="code-digit">20</span>[/csharp]
Observe the difference between above two examples. Lambda Expression reduces the code and decreases the burden on the programmer.
Types of Lambda Expression
Types
There are two categories under the Lambda Expression.
- Expression Lambdas
- Statement Lambdas
Description
See the syntax of the Lambda Expression. The right-hand side of the syntax i.e expression is called as
Expression Lambdas. Expression Lambdas are used in the
Expression Trees. Mainly the Expression Lambda returns the result of the expression.
Note
If we you are working in the outside of the .Net Framework. Then you should not use method calls in the lambda expression.[Referenced in MSDN]
Example
[csharp]
delegate int cube(int x);
static void main()
{
cube obj = a =<a * a * a;//calculates the cube value of given value
int Result = obj(2); // pass the value to lambda expression
Console.WriteLine("Cube Value is" + Result); //displays the result
}
[/csharp]
Description
Statement Lambdas is also in the right-hand side of the Lambda Operator. But, Statement Lambdas contains two or more statements which are enclosed in the braces.
Syntax
(Arguments)=>{Statements;}
Statement Lambdas are not used for constructing Expression Trees.
Working with Object Initializer
Description
Object initializer is a new feature of C# 3.0 version. Object initializer is used to simplify the object construction.
See the below example which shows a normal object declaration.
Example
[csharp]
class person
{
//Properties
public int Name { get; set; }
public string Age { get; set; }
}
//To create an object for the above class, we can write the following piece of code in C# 2.0
Person obj = new Person();
obj.Name="James";
obj.Age=30;
[/csharp]
But In C# 3.0, it is provided with the object initializer which reduces a little burden.
See the below code to know Object initializer.
[csharp]
class person
{
//Properties
public int Name { get; set; }
public string Age { get; set; }
}
Person obj=new Person{Name="James",Age=30};
[/csharp]
One can also use the nested concept here. That means, one can declare the object with in the object by using this object initializer.
Working with collection initializer
Description
Collection initializer is also a new feature which is introduced in the C# 3.0. Collection initializer is used to initialize the collection.
Types
The C# supports 3 types of collections.
- Normal Collections
- Specialized Collections
- Generic Collections
Normal Collections are like Array list, Stack, Queue, and Hash Table.
Specialized Collections are like List Dictionary, String Dictionary, and String Collection.
Generic Collections are like following
List()
Stack()
HashList()
Syntax
CollectionType<datatype> CollectionName=new CollectionType<datatype>{Initializing values separeted with ','};
Example
[csharp]
class Employee
{
// Auto-implemented properties.
public int EmpId { get; set; }
public string EmpName { get; set; }
public int EmpAge { get; set; }
}
class Example
{
static void main()
{
List<Employee> employee= new List<Employee>()
{
new Employee{EmpId=1,EmpName="James",EmpAge=23}
new Employee{EmpId=2,EmpName="Jan",EmpAge=43}
};
foreach(var x in employee)
{
Console.WriteLine(+x.EmpId+x.EmpName+x.EmpAge);
}
Console.ReadLine();
}
}
[/csharp]
Description
A Query is a type of language which is used to communicate with the Database and returns some Output or Data.
In LINQ, a Query is always will work on some data source which is inherited from the
iEnumerable interface.
LINQ Query contains 3 parts.
- From Clause
- Select Clause
- Where Clause
Note
Where Clause is optional. Select Clauses from mandotory clauses.
Methods
To execute the Query, there are two methods in LINQ.
- Differed Execution
- Forced Immediate Execution
Differed Execution
In this method, Query will be executed when a foreach loop is iterated. As long as the loop is being iterated query will be running. To print the elements, One have to use the for each loop.
[csharp]
foreach(var x in R)
{
Console.WriteLine(X+"");
}
[/csharp]
Forced Immediate Execution
In this method, Query will be run and it will return the result immediately. If one want to print the count of elements, Then write the code as shown below.
[csharp]
Console.WriteLne("Count of Elemts is"+R.Count());
[/csharp]
Here, when using R.Count() immediately Query will be run & will return the result, and query will be run only once.
Steps to work with LINQ Query
Step 1
Obtain the Data Source.
Example: List<int> L1=new List<int>{1,2,3,4,5}
Step 2
Prepare Query.
Example: var R= from Num in L1 where Num% 2==0 select Num;
Step 3
Execute the Query.
Description
OR Mapping Tool means Object Relational Mapping Tool. OR Mapping Tool is used to build a bridge between Database and the Object Oriented Programming(C# or VB).
Description
Data Context Class also contains two methods.
- Insert on Submit (Table Class Type)
- Delete on Submit (Table Class Type)
Insert on Submit
Insert on
Submit is used to insert a record into the respective table when the data context class sends the request to database.
Delete on Submit
Delete on submit is used to
delete a record from the respective table when the data context class sends the request to database.