Web Design that taps into the haromny and vision of your dreams.

LINQ: .NET Language Integrated Query

By on in Coding

1,122 words, estimated reading time 6 minutes.

Introduction to Programming with C# Series
  1. Introduction to Programming with C# 7
  2. C# Programming Fundamentals
  3. Introduction to Object-Oriented Programming
  4. C# Object-Oriented Programming Part 2
  5. Flow Control and Control Structures in C#
  6. C# Data Types, Variables and Casting
  7. C# Collection Types (Array, List, Dictionary, Hash Table)
  8. C# Operators
  9. Using Data in C# 7 with ADO.Net & Entity Framework
  10. LINQ: .NET Language Integrated Query
  11. Error and Exception Handling in C#
  12. Advanced C# Programming Topics
  13. Reflection in C#
  14. What Are ASP.Net Webforms
  15. Introduction to ASP.Net MVC
  16. Windows Application Development
  17. Assemblies in C#
  18. Working with Resources Files, Culture & Regions
  19. Regular Expressions in C#
  20. Introduction to XML with C#
  21. Complete Guide to File Handling in C#

LINQ (Language-Integrated Query), is a technology built into the .NET framework which will allow you to easily query and manipulate data across various sources in a consistent manner. It doesn't matter if the data is an array or a database, the methods and syntax are the same.

LINQ is extremely powerful for working with data and you can do a lot of things by simply chaining commands on one line.

In this example, we can select from an array all the names with 8 or fewer characters in length and order them alphabetically.

var names = new List<string>()  
{  
    "Kealan Pemberton",  
    "Kurtis Hayward",  
    "Hilary Bray",  
    "Nylah Fitzpatrick",
    "Brandon Hendrix",
    "Najma Pike",
    "Milosz Hester",
    "Ayda Reilly"
};  
 
var filteredNames = from name in names where name.Length <= 12 orderby name.Length select name;
 
foreach (var name in filteredNames)  
    Console.WriteLine(name);

Query Syntax vs. Method Syntax

LINQ statements can be written in one of two ways. The first, query syntax, we have seen above and is similar to the syntax used in SQL. The second method is more procedural, using methods to represent query functions. Here are two examples of the different syntaxes.

Query Suntax

var lastNames = from person in persons
where person.Age > 12
orderby person.LastName
select person.LastName;

Method Syntax

var lastName = persons
  .Where(person => person.Age > 12)
  .OrderBy(person => person.LastName)
  .Select(person => person.LastName);

In the query syntax, the person is declared once and used in the where, orderby, and select clauses. Using the method syntax you have to redeclare person each time in the lambda expressions.

At the end of the day the compiler processes the query, there isn't any performance difference so the choice of which to use is up to the developer.

Personally, I prefer method syntax and I find it good for when I want to generate LINQ queries dynamically with expression trees and such. Query syntax is better for when I'm doing complicated queries with many lets, joins, and nested projections.

For most of the tutorials on this site, I'll be using method syntax.

Filtering Data

One of the most basic operations you can perform on a set of data is to filter some of it out.

var names = new List<string>()  
{  
    "Kealan Pemberton",  
    "Kurtis Hayward",  
    "Hilary Bray",  
    "Nylah Fitzpatrick",
    "Brandon Hendrix",
    "Najma Pike",
    "Milosz Hester",
    "Ayda Reilly"
};  
 
var filteredNames = names.Where(x => x.Length <= 12)
 
foreach (var name in filteredNames)  
    Console.WriteLine(name);

This simply filters out everything where the length is greater than 12.

We can add multiple conditions to the where clause to further filter the results.

var filteredNames = names.Where(x => x.Length <= 12 && x.Length > 5)

We can also filter results to check that a value is contained, or not contained, within another list of predefined values.

var numbers = new List<int>()
{
    1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377
};
 
var excludedNumbers = new List<int>()
{
    21, 89
};
 
var validNumbers = numbers.Where(n => !excludedNumbers.Contains(n));
 
foreach (var n in validNumbers)
    Console.WriteLine(n);

Sorting Data

Another powerful and hugely useful method LINQ provides is data sorting. We can use OrderBy and OrderByDescending to sort our data.

var unorderedNumbers = new List<int>()
{
    1, 13, 144, 2, 21, 233, 3, 34, 377, 5, 55, 8, 89
};
 
var orderedNumbers = unorderedNumbers.OrderBy(x => x);

We can also perform operations on complex objects as well.

class person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
 
var persons = new List<person>()
{
    new person()
    {
        Name = "Kealan Pemberton",
        Age = 55
    },
    new person()
    {
        Name = "Kurtis Hayward",
        Age = 21
    },
    new person()
    {
        Name = "Hilary Bray",
        Age = 34
    }
};
 
var sortedPersons = persons.OrderBy(x => x.Age);

Limiting Data

Now we have filtered and sorted the data, we can limit the number of records. This is especially useful when using a database as a data source because it often involves huge amounts of rows, which are resource consuming to fetch.

The methods for limiting records are called Take() and Skip(), and in combination, they are great for doing pagination on a website.

Take specifies the number of records to return, and Skip specifies the number of results to skip before taking the records.

var names = new List<string>()  
{  
    "Kealan Pemberton",  
    "Kurtis Hayward",  
    "Hilary Bray",  
    "Nylah Fitzpatrick",
    "Brandon Hendrix",
    "Najma Pike",
    "Milosz Hester",
    "Ayda Reilly"
};  
 
var names = names.Skip(1).Take(2).ToList();

For pagination, you often have a page size and a current page number.

var names = new List<string>()
{
    "Kealan Pemberton",
    "Kurtis Hayward",
    "Hilary Bray",
    "Nylah Fitzpatrick",
    "Brandon Hendrix",
    "Najma Pike",
    "Milosz Hester",
    "Ayda Reilly"
};
 
var pageSize = 5;
var currentPage = 1;
var results = names.Skip(pageSize * currentPage).Take(pageSize);

Data Transformations

Finally, we may wish to transform the original data types to another type as part of the query. We can do this using the Select method. Consider the persons class previously and suppose we just want a list of names. We can select just the name part to return a list of strings.

class person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
 
var persons = new List<person>()
{
    new person()
    {
        Name = "Kealan Pemberton",
        Age = 55
    },
    new person()
    {
        Name = "Kurtis Hayward",
        Age = 21
    },
    new person()
    {
        Name = "Hilary Bray",
        Age = 34
    }
};
 
List<string> namesOnly = persons.Select(x => x.Name).ToList();

Grouping Results

When you group data, you take a list of something and then divide it into several groups, based on one or several properties. With LINQ, this is very easy, even though the use of the GroupBy() method can be a bit confusing in the beginning.

var persons = new List<person>()
{
    new person()
    {
        Name = "Kealan Pemberton",
        Age = 55,
        Country = "GB"
    },
    new person()
    {
        Name = "Kurtis Hayward",
        Age = 21,
        Country = "GB"
    },
    new person()
    {
        Name = "Hilary Bray",
        Age = 34,
        Country = "US"
    }
};
 
var nameGroupedByCountry = persons.GroupBy(user => user.Country);
foreach (var group in nameGroupedByCountry)
{
    Console.WriteLine("People from " + group.Key + ":");
    foreach (var person in group)
        Console.WriteLine("- " + person.Name);
}

Chaining LINQ Querues

Now we have seen the different methods, we can chain them together to sort, filter, page and select results in a single query.

var persons = new List<person>()
{
    new person()
    {
        Name = "Kealan Pemberton",
        Age = 55,
        Country = "GB"
    },
    new person()
    {
        Name = "Kurtis Hayward",
        Age = 21,
        Country = "GB"
    },
    new person()
    {
        Name = "Hilary Bray",
        Age = 34,
        Country = "US"
    }
};
 
List<string> namesOnly = persons.Where(x => x.Name.Length >= 12).OrderBy(x => x.Name).Take(3).Skip(5).Select(x => x.Name).ToList();

Last updated on: Thursday 11th October 2018

 

Comments

Have a question or suggestion? Please leave a comment to start the discussion.

 

Leave a Reply

Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Your email address will not be published.