TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# LINQ Examples: System.Linq and Extensions

These C# examples use the System.Linq namespace. They focus on extension methods and query expressions.

LINQ. A query asks for something.

It asks for a sorted sequence of ints greater than 10. This can be done with loops, if-tests and appends. LINQ reduces this.

This technology, Language Integrated Query, introduces extension methods. These work on Lists and arrays. We even use them on collections not yet in memory.

Example: We use the Average extension method to average all the elements in an int array. A double value is returned.

Tip: The Average method is implemented as an extension method within the .NET Framework. Extension methods have special syntax.

Extension Method

Based on:

.NET 4.5

C# program that uses LINQ extension

using System;
using System.Linq;

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

Output

4

Convert. Some extension methods in LINQ convert from an IEnumerable to another type. They convert to an array, Dictionary, List or Lookup.

ToArrayToDictionaryToListToLookup

Mutate. These methods filter or mutate. They change the elements in your query in some way. We remove unneeded elements, add new ones, or change other aspects of the elements themselves.

AsEnumerableAsParallelCastConcatContainsDefaultIfEmptyDistinctElementAtElementAtOrDefaultExceptFirstFirstOrDefaultGroupByGroupJoinIntersectJoinLastLastOrDefaultOfTypeOrderByOrderByDescendingReverseSelectSelectManySingleSingleOrDefaultUnionWhereZip

Skip and take. These extension methods are useful. They eliminate the need for custom code to check ranges. Skip passes over the first elements.

Skip, SkipWhileTake, TakeWhile

Computation. LINQ also provides computational methods. These act upon a certain query and then return a number or other value. These can also simplify code.

AggregateAllAnyAverageCountSequenceEqualSum

Max and min. We can search a collection for its largest (max) or smallest (min) value. This is effective for many value types. Which tower is the tallest?

Max, Min

Enumerable. The Enumerable type has some useful static methods. If you need an IEnumerable collection of a range or a repeated element, consider Range or Repeat.

Empty: The Empty method returns an empty enumerable collection. This can be useful as a "dummy" value.

Empty

Range: The Range method provides an enumerable collection that progresses from one value to another.

Range

Repeat: This method is repetitive—that is why it is called Repeat. It creates an enumerable collection full of one element.

Repeat

Query. A query expression uses declarative clauses. These specify the results we want, not how we are to achieve them. To start, we use a query expression on an array of integers.

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

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

In the query, we select elements from an array in descending order (high to low). We filter out elements <= 2. In the loop, we evaluate the expression and print the results.

Var

C# program that uses query expression

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

Keywords. Query expressions use a whole new set of keywords. These are contextual keywords. This means they only have meaning in query expressions.

ascendingdescendinggroupjoinletorderbyselect new

LINQ versus loop. LINQ has a performance cost. For small numeric operations, it introduces considerable overhead. For larger operations, this change is less important.

Benchmark: We count all elements in an array greater than or equal to 10 with LINQ and with a for-loop.

Result: The LINQ version is nearly ten times slower. For hot numeric loops, LINQ is a poor choice.

C# program that benchmarks LINQ, for-loop

using System;
using System.Diagnostics;
using System.Linq;

class Program
{
    const int _max = 1000000;
    static void Main()
    {
	int[] values = { 10, 0, 1, 1, 20, 300, 400, 4 };

	// Version 1: use LINQ.
	var s1 = Stopwatch.StartNew();
	for (int i = 0; i < _max; i++)
	{
	    int count = CountLinq(values);
	}
	s1.Stop();

	// Version 2: use for-loop.
	var s2 = Stopwatch.StartNew();
	for (int i = 0; i < _max; i++)
	{
	    int count = CountFor(values);
	}
	s2.Stop();
	Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) /
	    _max).ToString("0.00 ns"));
	Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) /
	    _max).ToString("0.00 ns"));
	Console.Read();
    }

    static int CountLinq(int[] values)
    {
	// Count values greater than or equal to 10 with LINQ.
	return (from x in values
		where x >= 10
		select x).Count();
    }

    static int CountFor(int[] values)
    {
	// Count values greater than or equal to 10 with a loop.
	int count = 0;
	for (int i = 0; i < values.Length; i++)
	{
	    if (values[i] >= 10)
	    {
		count++;
	    }
	}
	return count;
    }
}

Results

111.83 ns:    LINQ expression, Count()
 10.86 ns:    For-loop, if

Books. In query languages, we express what we want, not how it is to happen. The query language, not the programmer, is concerned with the exact implementation details.

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.

Structure and Interpretation of Computer Programs

LINQ is a powerful feature. Its methods and query expressions often improve the readability of programs. And they sometimes lead to new, delayed, superior algorithms.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf