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 <'a> 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.

devx-admin

devx-admin

Share the Post:
Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India,

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1