C# LINQ Examples

Array Collections File String Windows VB.NET Algorithm ASP.NET Cast Class Compression Convert Data Delegate Directive Enum Exception If Interface Keyword LINQ Loop Method .NET Number Regex Sort StringBuilder Struct Switch Time Value

System.Linq namespace

Imperative code describes how to complete an algorithm step-by-step. Declarative code instead describes the end result of that algorithm. LINQ is a declarative syntax form that was introduced into the C# language. It makes some computational tasks easier.

We call this language the query language, because it is very useful for retrieving information from data bases by formulating queries, or questions, expressed in the language. Abelson & Sussman, p. 440

System.Linq

LINQ—language integrated query—introduces many different extensions methods to your standard C# environment. For example, you can use the Average extension method to average all the elements in a collection. It works on Lists, arrays, and even collections that are not yet in memory.

Program that uses LINQ extension [C#]

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	int[] array = { 1, 3, 5, 7 };
	Console.WriteLine(array.Average());
    }
}

Output

4

Conversion

Conversion or change

These extension methods perform a conversion from an IEnumerable collection into a certain collection: an array, Dictionary, List, or Lookup data structure. We describe the methods, which are some of the most useful in the System.Linq namespace.

ToArray ToDictionary ToList ToLookup

Overview: These C# examples show how to use the System.Linq namespace. They focus on extension methods and then query expressions.

Mutation

These methods filter or mutate one or more collections. In other words, these will change the elements in your query in some way: by removing unneeded elements, by adding new elements, or by changing other aspects of the elements themselves.

Select method call AsEnumerable AsParallel Cast Concat DefaultIfEmpty Distinct ElementAt ElementAtOrDefault Except First FirstOrDefault GroupBy GroupJoin Intersect Last LastOrDefault OfType OrderBy OrderByDescending Reverse Select SelectMany Single SingleOrDefault Union Where ZipSkip illustration

Skip and Take methods. The Skip and Take extension methods are particularly useful, as they eliminate the need for you to compose custom code to check ranges. They are recommended in a variety of contexts in your C# programs.

Skip SkipWhile Take TakeWhile

Computation

Another function that LINQ provides is computational methods: these act upon a certain query and then return a number or other value. These can also simplify your code, by eliminating the requirement of computing values such as averages yourself.

Any method Aggregate All Any Average Count SequenceEqual Sum

Max and Min. You can search a collection for its largest (max) or smallest (min) value. This is effective for many value types, such as strings and numbers.

Max Min

Enumerable

The Enumerable type presents some static methods that can be very useful in certain situations, as we reveal in these examples.

Empty Range Repeat

Query

Find icon

Next, let's explore query expressions in the C# language. Query expressions are built with declarative clauses that specify the results you want, not how you want to achieve them. Let's check out this program that uses a query expression on an in-memory array of integers.

Imperative: You describe how to accomplish the task by indicating each step in code.

Declarative: You describe the final result needed, leaving the steps up to the query language.

Program that uses query expression [C#]

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	int[] array = { 1, 2, 3, 6, 7, 8 };
	// Query expression.
	var elements = from element in array
		       orderby element descending
		       where element > 2
		       select element;
	// Enumerate.
	foreach (var element in elements)
	{
	    Console.Write(element);
	    Console.Write(' ');
	}
	Console.WriteLine();
    }
}

Output

8 7 6 3

Description. In the query expression, we select all the elements from the array in descending order (high to low) and then filter out elements less than or equal to 2. In the foreach-loop, we evaluate the expression and print the results.

Query keywords

Let contextual keyword

Query expressions use a whole new set of keywords. These are contextual keywords, meaning that they only have meaning in query expressions. These query clauses are described in more detail.

ascending descending group join let orderby select new

Misc.

Miscellaneous

One additional example of LINQ found here is how you can construct an HTML sitemap with queries on a web site. This is not an ideal piece of code, but nonetheless interesting.

Sitemap Uses LINQ

Summary

The C# programming language

Though it typically reduces performance, LINQ methods and query expressions in the C# language can improve the readability of your programs and lead to new algorithmic approaches. With lazy evaluation, you can even delay expensive operations, leading to more immediate results.

Dot Net Perls