How to Use Linq

Mehulthakkar1
Posted by in LINQ category on for Beginner level | Views : 23265 red flag
Rating: 5 out of 5  
 3 vote(s)

This is the article which will explain how to use linq
Table of Contents

Introduction

Linq Query Operators

Query Expression

Simple Query Expression

Multipart Query Expression

Extension Methods

Different Execution

Immediate Execution

Generic Collections

Nongeneric Collections

OfType

Query Expressions

Enumerable Type and Lambdas

Enumerable Type and Anonymous Method

Enumerable Type and Row Delegates

Introduction

Linq ( Language Integrated Query) provide you command over manipulating data. Using Linq we can write the query expression in code. With the use of Linq we can manipulate any object which is implemented by the IEnumerable<T> interface, XML, Dataset or relational database.


The core Linq assemblies are as follows:
System.Core.dll :- The core LINQ API.
System.Data.Linq.dll :- LINQ with relational databases (LINQ to SQL).
System.Data.DataSetExtensions.dll :- ADO.NET types into the LINQ programming paradigm (LINQ to DataSet).
System.Xml.Linq.dll :- LINQ with XML document data (LINQ to XML).

System.Linq is the name space which is defined in System.Core.dll. This will be used to any sort of Linq Programming.

Linq Query Operators


from, in :- Used to start the LINQ expression.
where :- Used to filter the data.
select :- Used to select the data.
join, on, equals, into :- Performs joins based on specified key.
orderby, ascending, descending :- Allows the data to be ordered in ascending or descending order.
group, by :- Data grouped by a specified value.

Query Expression
Simple Query Expression

LINQ query expression is built using the from, in and select operators:
var result = from item in container select item;
Find the example here:

string[] Weekdays = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; 
IEnumerable<string> WeekdaysWithLength = from W in Weekdays where W.Length> int.Parse(textBox1.Text) select W;
listBox1.Items.Clear();
foreach (string str in WeekdaysWithLength)
listBox1.Items.Add(str);
Multipart Query Expression

To filter the data, where operator can be used like:
var result = from item in container where Boolean expression select item;
Find the example here:

string[] Weekdays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
//see the above code, the IEnumerable<string> WeekdaysWithLength is the explicit object,here var WeekdaysWithLength is implicit object, which will convert by assign type.
var WeekdaysWithLength = from W in Weekdays where W.Length > int.Parse(textBox1.Text) orderby W select W;
listBox1.Items.Clear();
foreach (string str in WeekdaysWithLength)
listBox1.Items.Add(str);
Extension Methods

Linq provides a set of generic extension methods e.g. Aggregate<T>(), Max<T>(), Distinct<T>() etc.
Find the example here:

string[] Weekdays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
//check with button1 and button2 click events, here now result would be converted in string array.
string[] WeekdaysWithLength = (from W in Weekdays where W.Length > int.Parse(textBox1.Text) orderby W descending select W).Distinct<string>();
listBox1.Items.Clear();
foreach (string str in WeekdaysWithLength)
listBox1.Items.Add(str);
Different Execution

LINQ query expressions are not actually evaluated until you iterate over the contents, so once apply the expression using Linq and use it multiple times with/without changes.
Find the example here:

int[] ar = {10,20,30,40,2,34,6,7,89 };
IEnumerable<int> a = from N in ar where N < 10 select N;
foreach (int x in a)
MessageBox.Show(x.ToString());
ar[0] = 5;
MessageBox.Show("Assign ar[0] =5; Now Refiltering...");
foreach (int x in a)
MessageBox.Show(x.ToString());
Immediate Execution

Linq provides extension methods such as ToArray<T>, ToList<T>() etc, which converts Linq query result in strong typed container. Once converted in strong type, Linq is not connected for longer.
Find the example here:

string[] Weekdays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
//check with button1 and button2 click events, here now result would be converted in string array.
string[] WeekdaysWithLength = (from W in Weekdays where W.Length > int.Parse(textBox1.Text) orderby W descending select W).ToArray<string>();
listBox1.Items.Clear();
foreach (string str in WeekdaysWithLength)
listBox1.Items.Add(str);

Generic Collections

Linq query expression can manipulate the data with members of System.Collection.Generic namespace.
Find the example here:

Create a Car class like
class Car
{
public string PetName = string.Empty;
public string Color = string.Empty;
public int Speed;
public string Make = string.Empty;

public override string ToString()
{
return string.Format("PetName: {0}, Color:{1}, Speed:{2}, Brand:{3}", PetName, Color, Speed, Make);
}
}

Use the above class in your form or page.
List<Car> myCars = new List<Car> { 
new Car{ Color= "Silver", Make="BMW", PetName="Henry", Speed=100},
new Car{ Color= "Tan", Make="BMW", PetName="Daisy", Speed=90},
new Car{ Color= "Black", Make="VW", PetName="Mary", Speed=55},
new Car{ Color= "Rust", Make="Yugo", PetName="Clunker", Speed=5},
new Car{ Color= "White", Make="Ford", PetName="Melvin", Speed=43}
};

List<Car> fastCars = (from fCar in myCars where fCar.Speed > 55 select fCar).ToList<Car>();
foreach (Car c in fastCars)
listBox2.Items.Add(c.PetName);
Nongeneric Collections

Linq provides a medium to filter out the nongeneric collection. For that we have to use OfType<T>() method which will convert the nongeneric collection in IEnumerable type.
Find the example here:

// non generic collection of Car objects
ArrayList arCars = new ArrayList{ 
new Car{ Color= "Silver", Make="BMW", PetName="Henry", Speed=100},
new Car{ Color= "Tan", Make="BMW", PetName="Daisy", Speed=90},
new Car{ Color= "Black", Make="VW", PetName="Mary", Speed=55},
new Car{ Color= "Rust", Make="Yugo", PetName="Clunker", Speed=5},
new Car{ Color= "White", Make="Ford", PetName="Melvin", Speed=43}
};

//convert non generic car object collection to enumerable
IEnumerable<Car> myCars = arCars.OfType<Car>();
List<Car> fastCars = (from fCar in myCars where fCar.Speed > 55 select fCar).ToList<Car>();
foreach (Car c in fastCars)
listBox3.Items.Add(c.PetName);
OfType

This method can be used to get the generic collection from nongeneric type. Also it is helpful in get the particular type of data from nongeneric collection.
Find the example here:

// Extract the ints from the ArrayList.
ArrayList myStuff = new ArrayList();
myStuff.AddRange(new object[] { 10, 400, 8, false, new Car(), "string data" });
IEnumerable<int> myInts = myStuff.OfType<int>();
// Prints out 10, 400, and 8.
foreach (int i in myInts)
{
Console.WriteLine("Int value: {0}", i);
}
Query Expressions
Enumerable Type and Lambdas

Linq query operators are the shorthand version of the extension methods of Enumerable type.
Find the example here:

List<Car> arCars = new List<Car>{ 
new Car{ Color= "Silver", Make="BMW", PetName="Henry", Speed=100},
new Car{ Color= "Tan", Make="BMW", PetName="Daisy", Speed=90},
new Car{ Color= "Black", Make="VW", PetName="Mary", Speed=55},
new Car{ Color= "Rust", Make="Yugo", PetName="Clunker", Speed=5},
new Car{ Color= "White", Make="Ford", PetName="Melvin", Speed=43}
};
List<Car> fastCars = arCars.Where(c => c.Speed > 55).Select(c => c).ToList<Car>();
listBox4.DataSource = fastCars;

Here we have used a lambda expression rather than using linq expression. Here we have specified “c” parameter which is processed by “c.Speed > 55” which results in Boolean return type. To return the value of this, Where method has implicitly typed.  

Enumerable Type and Anonymous Method

Lambda expressions also provide the anonymous method, which can be created using Func<> delegate. This is equivalent to lambda expressions and linq expressions.
Find the example here:

List<Car> arCars = new List<Car>{ 
new Car{ Color= "Silver", Make="BMW", PetName="Henry", Speed=100},
new Car{ Color= "Tan", Make="BMW", PetName="Daisy", Speed=90},
new Car{ Color= "Black", Make="VW", PetName="Mary", Speed=55},
new Car{ Color= "Rust", Make="Yugo", PetName="Clunker", Speed=5},
new Car{ Color= "White", Make="Ford", PetName="Melvin", Speed=43}
};
Func<Car, bool> searchFilter = delegate(Car c)
{
return c.Speed > 55;
};
Func<Car, Car> itemToProcess = delegate(Car c)
{
return c;
};
List<Car> fastCars = arCars.Where(searchFilter).Select(itemToProcess).ToList<Car>();
listBox4.DataSource = fastCars;
Enumerable Type and Row Delegates

We can avoid the lambdas and anonymous and we can direct delegate in the extension methods.
Find the example here:

List<Car> arCars = new List<Car>{ 
new Car{ Color= "Silver", Make="BMW", PetName="Henry", Speed=100},
new Car{ Color= "Tan", Make="BMW", PetName="Daisy", Speed=90},
new Car{ Color= "Black", Make="VW", PetName="Mary", Speed=55},
new Car{ Color= "Rust", Make="Yugo", PetName="Clunker", Speed=5},
new Car{ Color= "White", Make="Ford", PetName="Melvin", Speed=43}
};
List<Car> fastCars = arCars.Where(
delegate(Car c)
{
return c.Speed > 55;
}
).Select(
delegate(Car c)
{
return c;
}
).ToList<Car>();
foreach (Car c in fastCars)
listBox4.Items.Add(c.PetName);
Page copy protected against web site content infringement by Copyscape

About the Author

Mehulthakkar1
Full Name: Mehul Thakkar
Member Level:
Member Status: Member
Member Since: 10/8/2009 11:06:06 PM
Country:


System Analyst Mehul Thakkar

Login to vote for this post.

Comments or Responses

Posted by: Bca1023 on: 7/12/2011 | Points: 25
Sir,
Is Linq used in real life nowadays very much or SQL and Object Relational Mapping is used?
Posted by: Vijayakumarp on: 3/23/2012 | Points: 25
Nice Example for Beginner ..

Login to post response

Comment using Facebook(Author doesn't get notification)