Introducing DotNetFunda.com on mobile http://m.dotnetfunda.com ! Be with DotNetFunda.com on the go !
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 2907 |  Welcome, Guest!   Register  Login
Home > Articles > LINQ > How to Use Linq

How to Use Linq

3 vote(s)
Rating: 5 out of 5
Article posted by Mehulthakkar1 on 12/30/2009 | Views: 9856 | Category: LINQ | Level: Beginner red flag


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);

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

Latest Articles from Mehulthakkar1
Experience:7 year(s)
Home page:
Member since:Thursday, October 08, 2009
Level:Starter
Status: [Member]
Biography:System Analyst
Mehul Thakkar
 Responses
Posted by: Bca1023 | Posted on: 12 Jul 2011 02:43:37 AM | Points: 25

Sir,
Is Linq used in real life nowadays very much or SQL and Object Relational Mapping is used?

Posted by: Vijayakumarp | Posted on: 23 Mar 2012 07:17:44 AM | Points: 25

Nice Example for Beginner ..

>> Write Response - Respond to this post and get points
Related Posts

The article demonstrates the different core concepts of LINQ to XML with an easy console application that will create an XML document dynamically.

This article deals with using LINQ to Xml in C#.

This Article demonstrate the basic functionality of Lambda Expression in C#(Console Application).

I got a chance to review the book titled "WCF 4.0 Multi-tier Services Development with LINQ to Entities" written by Mike Liu and published by Packt Publishing. This post highlights the featured covers in this book that is very useful for the developers.

In this article, we shall learn how to use transactions in ADO.NET Entity framework in simplified manner.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/21/2012 7:34:31 AM