Getting started with LINQ queries in C#

Dev

Getting started with LINQ queries in C#

by Brian Gammill

With the advent of C# 3.0, Microsoft introduced the Language Integrated Query (LINQ) feature to provide .NET developers the ability to query and transform data using any .NET language.  This data can come from XML documents, relational database tables, or other objects.  LINQ is quite flexible and is integrated with the .NET framework very well.  Additionally, visual studio provides Intellisense for auto-completion when working with LINQ and the compiler can perform syntax and type checking on query expressions.

Typically, in modern software development, data access is a large portion of the functionality of any application.  Developers often spend copious amounts of time retrieving data from a database, modifying the data, and inserting data back into the database.  Object-Relational Mapping tools like nHibernate can eliminate many of the pains of data access; however, learning an OR/M most likely requires the developer learn yet another API.  With LINQ, Microsoft designed a general, all-purpose query tool in the System.Linq namespace that contains a bevy of standard query operators to make life easier for software developers.  These operators can be used from any type that implements the IEnumerable interface. 

Below are just a couple of examples of what a developer can use LINQ for.  This is hardly an exhaustive list and should be considered quite introductory.

LINQ with objects:

class LINQQuerySample1
{
    static void Main()
    {
         // create a data source
        int[] numbers = new int[] { 203, 3, 151, 18, 107, 23, 17 };
 
        // create the query
        IEnumerable numbersQuery =
            from number in numbers
            where number > 24
            select number;  
 
        // execute the query
        foreach (int i in numbersQuery)
        {
            Console.Write(i + " ");
        }           
    }
}
// Output: 203 151 107

LINQ with Datasets:

SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(
                            "SELECT * FROM tblOrderShipments",
                            _connectionString);
DataTable orderShipments = new DataTable("tblOrderShipments");
sqlDataAdapter.Fill(orderShipments);

int orderShipmentsCount =
    (from os in orderShipments.AsEnumerable()
     where os.Field("ShipToZipCode") == "73132"
     select os).Count();

LINQ with XML:

//constructing XML via Xelement class in the System.Xml.Linq namespace
XElement employees =
  new XElement("employee",
    new XElement("employee", "Brian"),
    new XElement("employee", "Cole"),
    new XElement("employee", "Greg"),
    new XElement("employee", "Chris")
);
 
//after using the ToString method on the XElement above

  Brian
  Cole
  Greg
  Chris
 
//using the XML above in a LINQ query to find the number
// of employees named "Chris"
int numberOfEmployeesNamedChris =
  (from i in employees.Elements("employee")
   where i.Value == "Chris"
   select i).Count());
//returns 1 as there is only 1 employee named Chris

LINQ is a fabulous addition to the .NET platform and provides consistency by defining a set of standard query operators to work with data from various sources, including objects, relational databases, XML, and others.  The fact that LINQ is integrated very well with the .NET langugages and tools can definitely improve developer productivity and should be given serious consideration by any developer.  For more information, see the Getting Started with LINQ in C# guide at MSDN. 

More About the Author

Brian Gammill

Software Developer
Getting started with LINQ queries in C# With the advent of C# 3.0, Microsoft introduced the Language Integrated Query (LINQ) feature to provide .NET developers the ability to ...

See more from this author →

Subscribe to our newsletter

  • I understand that InterWorks will use the data provided for the purpose of communication and the administration my request. InterWorks will never disclose or sell any personal data except where required to do so by law. Finally, I understand that future communications related topics and events may be sent from InterWorks, but I can opt-out at any time.
  • This field is for validation purposes and should be left unchanged.

InterWorks uses cookies to allow us to better understand how the site is used. By continuing to use this site, you consent to this policy. Review Policy OK

×

Interworks GmbH
Ratinger Straße 9
40213 Düsseldorf
Germany
Geschäftsführer: Mel Stephenson

Kontaktaufnahme: markus@interworks.eu
Telefon: +49 (0)211 5408 5301

Amtsgericht Düsseldorf HRB 79752
UstldNr: DE 313 353 072