Introducing LINQ (1) What Is LINQ

[LINQ via C# series]

This LINQ series is from my 10 parts of LINQ via C# talks. And the poster designs for the events are here.

What is LINQ

Here is the roadmap of .NET and C#:

Date .NET Framework CLR C# IDE Introduced Features
February 13th, 2002 1.0 1.0 1.0 Visual Studio .NET 2002 Managed Code
April 3rd, 2003 1.1 1.1   Visual Studio .NET 2003 .NET Compact Framework, etc.
October 27th, 2005 2.0 2.0 2.0 Visual Studio 2005 Generics
November 21st, 2006 3.0       WCF, WPF, WF, WC
November 19th, 2007 3.5   3.0 Visual Studio 2008 LINQ
April 12th, 2010 4.0 4.0* 4.0 Visual Studio 2010 Dynamic programming, etc.

* Maybe the version number is 4, not 4.0.

LINQ stands for “Language INtegrated Query”. This is a definition from MSDN:

LINQ is a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities.

LINQ is rooted in Microsoft's research project. And LINQ was first released as a part of .NET Framework 3.5. Visual Studio 2008 / Visual Studio 2010 can be used to write LINQ code. All the samples of this series are written in Visual Studio 2010, because this series covers .NET 4.0.

First look of LINQ

C# can be used to write LINQ code to query in-memory .NET objects, data stored in rational database, XML, etc.

LINQ to Objects

LINQ to Objects enables code to perform LINQ operations on managed objects. Suppose there is a data source of integers, and the task is to find the positive integers from the source, and sort them from larger to smaller:

int[] source = new int[] { 0, -5, 12, -54, 5, -67, 3, 6 };

// Query from source to results.

foreach (int item in results)
{
    Console.WriteLine(item);
}

In C# 2.0, a normal implementation is like this:

int[] source = new int[] { 0, -5, 12, -54, 5, -67, 3, 6 };

List<int> results = new List<int>();
foreach (int integer in source)
{
    if (integer > 0)
    {
        results.Add(integer);
    }
}

Comparison<int> comparison = delegate(int a, int b)
                                    {
                                        return b - a;
                                    };
results.Sort(comparison);

foreach (int item in results)
{
    Console.WriteLine(item);
}

In C# 3.0+, this can be done with a new approach:

int[] source = new int[] { 0, -5, 12, -54, 5, -67, 3, 6 };

var results = from integer in source
              where integer > 0
              orderby integer descending
              select integer;

foreach (int item in results)
{
    Console.WriteLine(item);
}

Basically the above code has done three things:

  • Defines a collection of integers;
  • Declare a SQL-like query;
  • executes the query, iterates the query results, and prints the results.

This SQL-like code is precisely the LINQ code. Being different from the imperative code in the first sample, LINQ provide declarative style.

More differences and advancements will be mentioned later.

LINQ to SQL

According to Anders Hejlsberg:

In looking at the current and next generation of technologies, it has become apparent that the next big challenge in programming technology is to reduce the complexity of accessing and integrating information that is not natively defined using OO technology. The two most common sources of non-OO information are relational databases and XML.

LINQ to SQL provides the functionality to apply LINQ queries on SQL Server data.

Take the Northwind database as an example. Here are a Categories table and a Products table, which have a one to many relationship. To query the name and unit price of products in the “Beverages” category, the traditional ADO.NET approach would be like this:

Dictionary<string, decimal> results = new Dictionary<string, decimal>();

using (SqlConnection connection = new SqlConnection(
    @"Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True"))
using (SqlCommand command = new SqlCommand(
    @"SELECT Products.ProductName, Products.UnitPrice FROM 
    (
        Products
        LEFT JOIN Categories
        ON Products.CategoryID = Categories.CategoryID
    )
    WHERE Categories.CategoryName = @CategoryName", connection))
{
    command.Parameters.AddWithValue("@CategoryName", "Beverages");
    connection.Open();
    using (SqlDataReader reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            string productName = (string)reader["ProductName"];
            decimal unitPrice = (decimal)reader["UnitPrice"];
            results.Add(productName, unitPrice);
        }
    }
}

foreach (KeyValuePair<string, decimal> item in results)
{
    Console.WriteLine("{0}: {1}", item.Key, item.Value.ToString(CultureInfo.InvariantCulture));
}

This is the result:

Chai: 18.0000
Chang: 19.0000
Guaraná Fantástica: 4.5000
Sasquatch Ale: 14.0000
Steeleye Stout: 18.0000
...

LINQ can also work with data in SQL server:

using (NorthwindDataContext database = new NorthwindDataContext())
{
    var results = from product in database.Products
                  where product.Category.CategoryName == "Beverages"
                  select new
                            {
                                product.ProductName,
                                product.UnitPrice
                            };
    foreach (var item in results)
    {
        Console.WriteLine("{0}: {1}", item.ProductName, item.UnitPrice.ToString());
    }
}

The code looks much simplified. For example, declarative query similar with the LINQ to Objects sample is used, without providing the T-SQL string. And every item is strong typed as wished, no casting code needed.

LINQ to XML

According to MSDN:

LINQ to XML is a LINQ-enabled, in-memory XML programming interface that enables you to work with XML from within the .NET Framework programming languages.

Consider the scenario of working with XML data (Take my blog’s RSS feed as example):

<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
  <channel>
    <title>Dixin's Blog</title>
    <link>http://weblogs.asp.net/dixin/default.aspx</link>
    <!-- ... -->
    <item>
      <title>Title</title>
      <pubDate>Thu, 26 Nov 2009 05:01:00 GMT</pubDate>
      <!-- ... -->
      <category>C#</category>
      <category>.NET</category>
      <category>LINQ</category>
    </item>
    <item />
    <item />
    <item />
    <!-- ... -->
  </channel>
</rss>

LINQ also provides the capability to work with XML data. For example, to query the articles of the C# category, LINQ can also be used:

XDocument xml = XDocument.Load(@"http://weblogs.asp.net/dixin/rss.aspx");
var results = from item in xml.Root.Element("channel").Elements("item")
              where item.Elements("category").Any(category => category.Value == "C#")
              orderby DateTime.Parse(item.Element("pubDate").Value)
              select item.Element("title").Value;
foreach (var item in results)
{
    Console.WriteLine(item);
}

And this is the result:

C# Coding Guidelines (1) Fundamentals
C# Coding Guidelines (2) Naming
C# Coding Guidelines (3) Members
C# Coding Guidelines (4) Types
C# Coding Guidelines (5) Exceptions
C# Coding Guidelines (6) Documentation
C# Coding Guidelines (7) Tools
...

LINQ to Wikipedia

This last sample to show the capabilities of LINQ is to query data of Wikipedia with LINQ to Wikipedia. The following code searches Wikipedia with the keyword “LINQ”:

WikipediaContext datacontext = new WikipediaContext();

var results = from wikipedia in datacontext.OpenSearch
              where wikipedia.Keyword == "LINQ"
              select wikipedia;
foreach (var item in results)
{
    Console.WriteLine("{0} - {1}", item.Text, item.Url);
}

And the result is:

Language Integrated Query - http://en.wikipedia.org/wiki/Language_Integrated_Query
Linqing - http://en.wikipedia.org/wiki/Linqing
Linqu County - http://en.wikipedia.org/wiki/Linqu_County
Linquan County - http://en.wikipedia.org/wiki/Linquan_County
Linquo coax ranis - http://en.wikipedia.org/wiki/Linquo_coax_ranis
Linqpad - http://en.wikipedia.org/wiki/Linqpad
LINQ (card game) - http://en.wikipedia.org/wiki/LINQ_(card_game)
Lingua franca - http://en.wikipedia.org/wiki/Lingua_franca

The search becomes very simple, and easy to read.

LINQ via C#

According to Anders Hejlsberg’s speech “The Future of C#” on PDC 2008,

introducing-linq-what-is-linq-3

LINQ is the subject of .NET 3.5, and of course the subject of C# 3.0. Actually LINQ does provide a new programming paradigm for .NET.

The concept of LINQ consists of:

  • Native language features (like the query expression above) for managed languages, including C# 3.0+, VB.NET 9.0+, etc., so that programmers can smoothly write LINQ code to work;
  • Work on different kinds of data, such as query.

This “LINQ via C#” series is intent to introduce how to use LINQ and how does LINQ work in C# programming language.

Published Tuesday, November 24, 2009 1:00 PM by Dixin

Comments

# Zimo &raquo; Blog Archive &raquo; Understanding C# 3.0 Features (3) Type Inference

Pingback from  Zimo  &raquo; Blog Archive   &raquo; Understanding C# 3.0 Features (3) Type Inference

# 翻译:C# 3.0新特性详细介绍(3) 类型推导(Type Inference) _ 人猿的巢穴

Pingback from  翻译:C# 3.0新特性详细介绍(3) 类型推导(Type Inference)  _ 人猿的巢穴

# re: Introducing LINQ (1) What Is LINQ

Thursday, May 17, 2012 10:46 PM by GqahGSsdEOzCOiQd

k4XbEr Im thankful for the blog article. Want more.

Leave a Comment

(required) 
(required) 
(optional)
(required)