BITE SIZE C# – LINQ

LINQ or Language Integrated Query is part of the Microsoft .NET Framework and it adds native data querying capabilities to .NET languages.

LINQ allows the user to query:

  • Objects in Memory (i.e. collections such as lists) using LINQ to Objects
  • Databases using LINQ to Entities
  • XML using LINQ to XML
  • ADO.Net Datasets using LINQ to Datasets

LINQ can either be implemented using predefined extension methods or alternatively using LINQ Query Operators.

Below are three examples utilising LINQ Extension methods:

In this example a list of Book objects is filtered to return only the Objects where the price is less than 10.

List<Book> cheapBooks = books.Where(b=>b.Price < 10);

 

In this example a list of Book objects is filtered to return only the Objects where the price is less than 10 and additionally the newly created list of Book objects is sorted alphabetically based on the Title field.

List<Book> cheapBooks = books.Where(b=>b.Price < 10).OrderBy(b.Title);

 

In this example the cheapBooks list is filtered to only return the Titles of the books therein and these Titles are then inserted into a new list of strings.

List<string> cheapBooksTitles = cheapBooks.Select(b=>b.Title);

 

Multiple extension methods can be combined to ascertain the desired results, for example:

List<string> cheapBooksTitles = books.Where(b=>b.Price).OrderBy(b.Title);
                                   .Select(b=>b.Title);

 

LINQ query operators tend to be slightly more verbose, and the above example can be implemented with query operators as follows:

List<string> cheapBooksTitles = from b in books
                         where b.Price < 10
                         orderby b.Title
                         select b.Title;

 

Some common extension methods are:

Single

var book = books.Single(b=>b.Title == ”Building Robots”);

Returns a single object that matches the defined criteria. However note that in the event that none or more than one book matches the criteria specified an exception will be thrown.

 

SingleOrDefault

var book = books.SingleOrDefault(b=>b.Title == ”Building Robots”);

Returns a single object that matches the defined criteria, if more than one book matches the criteria specified an exception will be thrown, however if no books match the criteria the default value defined will be returned.

 

First

Returns the first object that matches the criteria, however if no matches are found an exception is thrown.

 

FirstOrDefault

Returns the first object that matches the criteria and if no match is found the default value will be returned.

 

Last

Returns the last object that matches the criteria, however if no matches are found an exception is thrown.

 

LastOrDefault

Returns the last object that matches the criteria and if no match is found the default value will be returned.

 

Max

var maxValue = books.Max(b=>b.Price);

Max is used with numeric values and will return the highest value that is contained in the Price field in the Book objects.

 

Min

var minValue = books.Min(b=>b.Price);

Min is another operation used with numeric values and will return the smallest value that is contained in the Price field in the Book objects.

 

Sum

var totalPrice = books.Sum(b=>b.Price);

Sum is used to add up all the values in a numeric field.

 

There are many other methods available to filter and manipulate data in LINQ and the possibilities for the utilisation of LINQ are nearly endless, for example

var bookSelection = books.Skip(2).Take(3);

The above example will skip the first two books in the books list and take the next three placing them into the newly created bookSelection list.

The best option to gain a better insight of what is possible with LINQ is to give it a try.

BITE SIZE C# – LINQ

One thought on “BITE SIZE C# – LINQ

  1. It seems odd at first to have this kind of querying capability when you have a perfectly good database but the moment you realise you can apply the same operations to collections and XML you see how much easier it can make your work. 🙂

    Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s