devxlogo

What’s New in C# 3.0? Part 2

What’s New in C# 3.0? Part 2

ith the release of Visual Studio 2008, Microsoft has updated the C# language to its latest version, 3.0. C# 3.0, contains several key language enhancements that support the recently-announced Language Integrated Query (LINQ) feature. Part 2 of this series picks up where Part 1 left off, walking you through C#’s new LINQ support features and providing a code examples that illustrate how to use them.

LINQ
One of the key additions to the .NET Framework is the support for Language Integrated Query (LINQ). LINQ allows you to manipulate data just like you manipulate database records using a query language like SQL. So instead of writing complex iterative loops to retrieve the data that you desire, you simply specify the data you want declaratively using LINQ and the compiler will do all the work for you.

LINQ to Objects
LINQ to Objects allows you to use LINQ to directly query any IEnumerable or IEnumerable collections directly. For example, suppose you have a collection of data stored in an array and you want to be able to retrieve a subset of the data quickly. In the old way of doing things, you’d write a loop and iteratively retrieve all the data that matches your criteria. This is time-consuming as you have to write all the logic to perform the comparison, and so on. With LINQ, you can declaratively write the condition using an SQL-like statement and the compiler will do the job for you.

To understand the usefulness of LINQ to Objects, suppose you have an array of type string that contains a list of names:

   string[] allNames = new string[] {"Jeffrey", "Kirby", "Gabriel",                                      "Philip", "Ross", "Adam",                                      "Alston", "Warren", "Garfield"};

Now, further suppose you need to print out all the names in this array that starts with the letter “G”. In this case, you can set up a loop and iteratively perform a comparison on each name. Things start to get more complex when you have more complex filtering rules. Using LINQ, you can specify the filter using the from clause, like this:

            IEnumerable foundNames =                from name in allNames                where name.StartsWith("G")                select name;

Notice that the code declares the foundNames variable of type IEnumerable. You can also use the new implicit typing feature in C# 3.0 to let the C# compiler automatically infer the type for you, like this:

            var foundNames =                from name in allNames                where name.StartsWith("G")                select name;

When this statement has been executed, foundNames will now contain a collection of names that starts with the letter “G”. It this case, it returns “Gabriel, Garfield”. You can now print out all the names in the collection, for example:

            foreach (string peopleName in foundNames)            {                Console.WriteLine(peopleName);            }

To can also use a more complex filter, such as the following:

            IEnumerable foundNames =                from name in allNames                where name.StartsWith("G") || name.Contains("by")                 orderby name                select name;

In this case, foundNames will now contain “Gabriel, Garfield, Kirby”. Note that the result is also sorted.

Another useful application of LINQ is in manipulating Windows Forms controls. Suppose you have a large number of controls on your form and you want to uncheck all the CheckBox controls without setting each individually. You can use the following code to do that using LINQ:

        //---retrieve all the checkbox controls in the current form---        IEnumerable checkBoxes = from Control ctrl in this.Controls                                          where ctrl is CheckBox                                          select ctrl;        //---uncheck all the checkbox controls---        foreach (CheckBox c in checkBoxes)        {            c.Checked = false;        }

LINQ to Dataset
Besides manipulating data in memory, LINQ can also be used to query data stored in structures like datasets and datatables. The following example (in C#) shows how the Authors table within the pubs database is loaded onto a Dataset object and then queried using LINQ:

            SqlConnection conn;            SqlCommand comm;            SqlDataAdapter adapter;            DataSet ds = new DataSet();            //---load the Employees table into the dataset---            conn = new SqlConnection(@"Data Source=.SQLEXPRESS;" +                   "Initial Catalog=pubs;Integrated Security=True");            comm = new SqlCommand("SELECT * FROM Authors", conn);            adapter = new SqlDataAdapter(comm);            adapter.Fill(ds);                        //---query for authors living in CA---            var authors = from author in ds.Tables[0].AsEnumerable()                          where author.Field("State") == "CA"                          select author;

To display the result, you can either bind the result to a DataGridView control using the AsDataView() method:

            //---bind to a datagridview control---            dataGridView1.DataSource = authors.AsDataView();

Or, iteratively loop through the result using a foreach loop:

            foreach (DataRow row in authors)            {                Console.WriteLine("{0} - {1}, {2}",                    row["au_id"], row["au_fname"], row["au_lname"]);            }

If you want to query the authors based on their contract status, use the following query:

            var authors = from author in ds.Tables[0].AsEnumerable()                          where author.Field("Contract") == true                          select author;

The earlier section mentioned the C# 3.0’s new anonymous types feature. Using this feature, you can define a new type without needing to define a new class. Here’s one good use of anonymous types. Consider the following statement:

Figure 1. An Anonymous Type: authors is an anonymous type with three fields.

        //---query for authors living in CA---       var authors = from author in ds.Tables[0].AsEnumerable()                     where author.Field("State") == "CA"                     select new {                         ID = author.Field("au_id"),                        FirstName = author.Field("au_fname"),                        LastName = author.Field("au_lname")                                          };

Here, you select all the authors living in the state of CA while simultaneously creating a new type consisting of three properties: ID, FirstName, and LastName. If you now type the word “authors”, IntelliSense will show you that authors is of type EnumerableRowCollection authors, and ‘a is an anonymous type containing the three fields (see Figure 1).

You can now print out the result using a foreach loop:

            foreach (var auth in authors)            {                Console.WriteLine("{0} - {1}, {2}",                    auth.ID, auth.FirstName, auth.LastName);            }

LINQ to SQL
The previous section showed you how to use LINQ to retrieve data from a dataset. A much easier way would be to use LINQ to SQL, which allows you to access SQL databases directly. Here is an example of how it works.

First, add a new item to your project. Select the LINQ to SQL Classes template (see Figure 2). Use the default name of DataClasses1.dbml.

Figure 2. Adding a Template: Adding a LINQ to SQL Classes template to the project.

In Server Explorer, establish a connection to the desired database and drag and drop the table with which you want to work onto the DataClasses1.dbml page (see Figure 3).

Visual Studio 2008 will now create a new class called DataClasses1DataContext (which derives from DataContext). This class allows you to programmatically connect to (and access) the authors table and it’s found in the DataClasses1.designer.cs file.

To use LINQ to retrieve the rows in the authors table, first create an instance of the DataClasses1DataContext class:

            DataClasses1DataContext dataContext =                new DataClasses1DataContext();

Then, use LINQ to select the required rows:

            var allAuthors = from a in dataContext.authors                             select a;
Figure 3. Adding a Table: Drag and drop the table you want to use (authors) onto the DataClasses1.dbml page.

Finally, you can print out the individual fields by directly accessing them via the various properties:

            foreach (var a in allAuthors){                Console.WriteLine("{0} - {1}, {2}",                    a.au_id, a.au_fname, a.au_lname);            }

To retrieve all authors living in Utah and then bind the result to a DataGridView control, use the following statements:

            DataClasses1DataContext dataContext =                new DataClasses1DataContext();            var allAuthors = from a in dataContext.authors                             where a.state=="UT"                             select a;            //---bind to a datagridview control---            dataGridView1.DataSource = allAuthors;

LINQ to XML
Another very cool capability of LINQ is its ability to manipulate XML documents. For example, suppose you want to create an XML document by hand, you can use the following code segment:

         XDocument library = new XDocument(            new XElement("Library",               new XElement("Book",                  new XElement("Title", "Professional Windows Vista " +                               "Gadgets Programming"),                  new XElement("Publisher", "Wrox")               ),               new XElement("Book",                  new XElement("Title", "ASP.NET 2.0 - A Developer's " +                               "Notebook"),                  new XElement("Publisher", "O'Reilly")               ),               new XElement("Book",                  new XElement("Title", ".NET 2.0 Networking Projects"),                  new XElement("Publisher", "Apress")               ),                new XElement("Book",                  new XElement("Title", "Windows XP Unwired"),                  new XElement("Publisher", "O'Reilly")               )            )         );

Notice that the indentation gives you an overall visualization of the document structure. To save the XML document to file, use the Save() method:

        library.Save("Books.xml");

To perform querying on the XML document, load the document from file and then use LINQ:

        XDocument LibraryBooks = new XDocument();        LibraryBooks = XDocument.Load("Books.xml");        IEnumerable OReillyBooks =            from b in LibraryBooks.Descendants("Book")            where b.Element("Publisher").Value == "O'Reilly"            select b.Element("Title").Value;        foreach (var book in OReillyBooks) {            Console.WriteLine(book);        }

The above code will generate the following output:

ASP.NET 2.0 - A Developer's NotebookWindows XP Unwired

Extension Methods
In the past, when you wanted to add additional methods to a class, you had to subclass the class and then add whatever methods you needed. In C# 3.0, you can just use the new extension methods feature to add a new method to an existing CLR type.

To see how extension methods work, consider the following example. Suppose you deal very frequently with the Point class and you want to be able to quickly find out the distance between two points. In this case, you might be better served by adding a new function called DistanceFromThisPointTo() to the Point class so it can return the distance between two Point objects. To do so, define a new static class and define the extension method (a static method) within it, like this:

    public static class MethodsExtensions    {        public static double DistanceFromThisPointTo(           this Point PointA, Point PointB)        {            return Math.Sqrt(                Math.Pow((PointA.X - PointB.X), 2) +                Math.Pow((PointA.Y - PointB.Y), 2));        }    }

Here, the first parameter of the extension method is prefixed by the Point, which indicates to the compiler that this extension method must be added to the Point class. The rest of the parameter list consists of the signature of the extension method. To use the extension method, you can simply call it from a Point object, like this:

    Using MethodsExtensions;    public partial class Form1 : Form    {        private void Form1_Load(object sender, EventArgs e)        {            Point ptA = new Point(3, 4);            Point ptB = new Point(5, 6);            Console.WriteLine(ptA.DistanceFromThisPointTo(ptB));        }       }

Partial Methods
In C# 2.0, you dealt with the concept of partial classes, in which the definition of a class could be split into two. In C# 3.0, this concept is extended to methods: partial methods. To see how partial methods work, consider the following example.

Suppose you have a partial Contact class that contains two properties?Name and Email:

public partial class Contact{    string _email;    public string Name { get; set; }    public string Email    {        get        {            return _email;        }        set        {            _email = value;        }    }}

Now, suppose you want to allow users of this partial class to optionally log the email address of each contact when its Email property is set. In this case, you can define a partial method called LogEmail(), as shown in Listing 1.

As you can see in Listing 1, you’ve defined a partial method named LogEmail() that gets called when a contact’s email is set via the Email property. Note that this method has no implementation. So where is LogEmail()‘s implementation? It can optionally be implemented in another partial class. For example, if another developer decides to use the Contact partial class, (s)he can define another partial class containing the implementation for the LogEmail() method:

public partial class Contact{    partial void LogEmail()    {        //---code to send email to contact---        Console.WriteLine("Email set: {0}", _email);    }}

And so now, when you instantiate an instance of the Contact class, you can set its Email property as follows and a line will be printed in the output window:

            Contact contact1 = new Contact();            contact1.Email = "[email protected]";

But what if there’s no implementation of the LogEmail() method? In that case, the compiler simply removes the call to this method and, thus, there is no change to your code.

Partial methods are useful when you are dealing with generated code. For example, suppose the Contact class is generated by a code generator. The signature of the partial method is defined in the class, but the implementation is totally up to you to decide if you need to.

Partial methods must adhere to the following rules:

  • They must begin with the partial keyword and the method must return void.
  • They can have ref parameters but not out parameters.
  • They are implicitly private and, therefore, cannot be virtual.
  • They cannot be extern, because the presence of the body determines whether they are defining or implementing.
  • They can have static and unsafe modifiers.
  • They can be generic; constraints are put on the defining partial method declaration, and may optionally be repeated on the implementing declaration.
  • Parameter and type parameter names do not have to be the same in the implementing declaration as in the defining declaration.
  • They cannot make a delegate to a partial method.

Up to Speed
Now that you’ve learned about all the new features available in C# 3.0, I hope they can help save you time and hassle in your next project.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist