Getting Started with Adobe After Effects - Part 6: Motion Blur

Upload Image Close it
Select File

Browse by Tags · View All
Data Access 5
.NET 2
VS2010 2
dot net 2

Archive · View All
May 2010 5
April 2010 3
May 2011 1
December 2010 1

Deepak Palkar's Blog

Getting Started with LINQ

May 2 2010 1:22AM by Deepak Palkar   

In this we’ll continue to discuss how to go about the SQL Server Data Access using various technologies. This post will discuss Microsoft Language Integrated Query, otherwise known as LINQ. I will discuss how it can be used to accomplish the same tasks we have discussed in previous posts. But before that it surely requires a good introduction to start with.

LINQ was introduced with .net 3.0 as one of the language enhancements. It uses generics, which was introduced in .net 2.0, thoroughly to accomplish what it was designed to do. LINQ is designed to query virtually any kind of data source which implements IEnumerable<T> interface. It allows you to query the data by emulating the SQL query expressions using any .net language you are comfortable with. Isn’t that amazing!!

Here's a very simple example to demonstrate the power of LINQ. Suppose we have a string array of names as follows.
string[] names = { "John Smith", "Jenny Banks", "Thomas Smith", "Krisha Davis", "Jason Kimber" };

We want to find the names which contains the string "Smith" in them. A typical code would look something like this.

private static List<string> SimpleSearch1(string[] names)
	List<string> LastNames = new List<string>();
	//Find people whose Last name is 'Smith'
	foreach (string name in names)
		if (name.Contains("Smith"))
	return LastNames;

But with LINQ, it would look something like this. This one is LINQ's Query Syntax.

private static List<string> SimpleLinq_QuerySyntax(string[] names)
	List<string> lastNames = (from name in names
                                      where name.Contains("Smith")
                                      select name).ToList<string>();

	return lastNames;

Same code above can be written using LINQ's Method Syntax like this.

private static List<string> SimpleLinq_MethodSyntax(string[] names)
	return names.Where(name => name.Contains("Smith")).ToList<string>();

In Method syntax of LINQ, you can see the use of Lambda Expressions. Initially when I was trying to learn LINQ, this particular thing really scared me. But once you understand that it’s just an shorthand way of using the anonymous functions, you feel much comfortable with it. Following is the simplified version of above function.

private static int[] ConvertCSVToIntArrayWithAnonymousFunction(string CSV)
    string[] numbers = CSV.Split(',');
    return numbers.Select(
                            delegate(string s) 
                                return Int32.Parse(s); 


For this example, I just used a simple string collection. But you can also use it with database or XML objects too. Because LINQ is so powerful, you should expect to see a log of systems and products become LINQ compatible. Virtually any data store would make a good candidate for supporting LINQ queries. This includes databases, Microsoft’s Active Directory, the registry, the file system, an excel file, and so on.
Microsoft has already identified the components in this section as necessary for LINQ as follows,

LINQ to Objects (which we saw above) is the name given to the IEnumerable<T> API for the Standard Query Operators. It is LINQ to Objects that allows you to perform queries against arrays and in-memory data collections.

LINQ to XML is the name given to LINQ API dedicated to working with XML. This interface was previously known as XLINQ in older prereleases of LINQ. Microsoft has added the necessary XML libraries to work with LINQ and they also had addressed deficiencies in the standard XML DOM to make it easier than ever to work with XML. You don’t have to create an XmlDocument just to work with a small piece of XML. Here’s a very good 5 minute overview about LINQ to XML.

LINQ to DataSet is the name given to the LINQ API for DataSets. many developers have lot of existing code relying on DataSets. Those who do will not be left behind, nor will they need to rewrite their code to take advantage of the power of LINQ. Here’s an excellent post from ADO.Net team about LINQ to DataSet.

LINQ to SQL is the name given to the IQueryable<T> API that allows LINQ queries to work with Microsoft’s SQL Server database. This interface was previously known as DLinq in older prereleases of LINQ. In this post Mr.. Scott Gu explores LINQ to SQL very much in detail.

LINQ to Entities is an alternative LINQ API that is used to interface with a database using the ADO.NET Entity Framework. It decouples the entity object model from the physical database by injecting logical mapping between the two. With this decoupling comes increased power and flexibility.

Now, having mentioned that LINQ is all about Data, there is a different side of LINQ. You can do a lot of tricky things with LINQ apart from just queries. For example, how many times you have to pass a string of comma separated values (CSV) or ids to a stored procedure, which you have received as a array or collection of integers? And many a times you have to convert a string of CSV into an integer array? I’ve had to do that often. Here’s how LINQ does it so slickly!

private static string ConvertToCSV(List<int> numbers)
	//Convert the integers to strings and then generate an array of strings on the fly! 
	string[] strNumbers = numbers.Select(i => i.ToString()).ToArray();
	return string.Join(", ", strNumbers);
private static int[] ConvertCSVToIntArray(string CSV)
	string[] numbers = CSV.Split(',');
	//Convert integers to strings and then generate an array of integers
	return numbers.Select(s => Int32.Parse(s)).ToArray();

To continue with our examples from previous posts, let me show you the differences between ADO.Net, Data Access Application Block (DAAB) and LINQ To SQL.

DataReader with ADO.Net
private void PopulateDropdown(string connectionString)
	string queryString = "SELECT CustomerID, CustomerName FROM dbo.Customers;";
	using (SqlConnection connection = new SqlConnection(connectionString))
		SqlCommand command = new SqlCommand(queryString, connection);
		SqlDataReader reader = command.ExecuteReader();
		// Call Read before accessing data.
		while (reader.Read())
		// Call Close when done reading.
DataReader with DAAB
private void PopulateDropdown()
	Database db = DatabaseFactory.CreateDatabase();

	string queryString = "SELECT CustomerID, CustomerName FROM dbo.Customers;";
        DbCommand dbCommand = db.GetSqlStringCommand(queryString);

        // The ExecuteReader call will request the connection to be closed upon
        // the closing of the DataReader. The DataReader will be closed 
        // automatically when it is disposed.

	using (IDataReader Reader = db.ExecuteReader(dbCommand))
		while (reader.Read())

LINQ to SQL in Action
private static void PopulateDropDown()
	DataContext db = new DataContext();
	foreach (Customer customer in db.Customers)

We'll get exactly the same results as what previous two technologies are doing, but as you can see, we are not using the efficiency of DataReader here, which is definitely possible with LINQ to SQL. In this post by Mr. Rick Strahls, he has demonstrated exactly the same.

For our second example in previous post where we were returning the DataSet object with GetDataSet() method, LINQ to SQL doesn't have a concept of returning DataSet, but if you really wish to do that, you can try doing that using extension methods, I have never tried it but here’s a post which can help if you wish to investigate further into it. LINQ to SQL itself returns Typed Table objects or ultimately the IEnumerable<T> which we can use directly for databinding as follows.

private static void BindControl()
    DataContext db = new DataContext();
    var customers = from c in db.Customers
                    where c.Region == "CA"
                    select c;

    GridView1.DataSource = customers;

In above code snippet, you noticed the var keyword, which actually infer the data type of customers variable. Along with var keyword, there are few more new language enhancements that came with LINQ. To name a few here, they are Object Initializers, Collection Initializers, Anonymous types, Extension Methods, Partial Methods etc. I have add a new post to discuss them a little further.

LINQ is a vast subject, there are number of books written on it, detailing almost every component that we just had a brief introduction here. If you are new to LINQ it’s a much better idea to get a book on it to get a better understanding. Till then please read more at msdn.

LINQ makes it delightful to work with the collections, may that be your regular .net collections or XML or database. It provides a high level abstraction of virtually any data. I hope you enjoy using it as much as I do.

Happy Coding!!

Related Posts


Deepak Palkar
182 · 1% · 269


Your Comment

Sign Up or Login to post a comment.

    Copyright © Rivera Informatic Private Ltd Contact us      Privacy Policy      Terms of use      Report Abuse      Advertising      [ZULU1097]