LINQ Using C# – LINQ Operators

LINQ (Language INtegrated Query) was introduced with of C# 3.0 and .NET Framework 3.5. LINQ enables developers to write structured type-safe queries over local object collections and remote data sources. In essence it is  SQL for C#.

LINQ allows for querying over any collection which implements IEnumerable<> (including arrays, lists, XML DOM, remote data objects such as tables in a SQL Server database). LINQ key strength is that it allows objects to be queried using SQL-like syntax while at the same time providing on the fly type error checking and intellisense in Visual Studio.

LINQ Basics

The fundamental units in LINQ are sequences and elements. A sequence is an object which implements IEnumerable ,an element is the items in the sequence. In the following example, places is a sequence, and hongkong, singapore , and shanghai are elements:

//
	string[] places = { "hongkong", "singapore", "shanghai" };

This is an example of a local sequence  as it represents a local collection of objects in memory. Query operators  are methods which transform  a sequence. Query operators accept inputs and emits an  output sequence which has been transformed. Enumerable in System.Linq has over 40 query operators which are implemented as static methods. These are called standard query operators (eg WHERE, COUNT, MIN, MAX).

LINQ WHERE

Where is probably the most common operator to use in LINQ. This example uses the WHERE operator to generate a list of the place names with more than 8 characters:

//WHERE example
string[] places = { "hongkong", "singapore", "shanghai" };
 IEnumerable filteredPlaces =
 System.Linq.Enumerable.Where (places, n => n.Length > 8);
foreach (string n in filteredPlaces)
Console.Write (n); // singapore

Query operators are extension methods and so we can use Where directly on places , so to simplify the example:

//WHERE example	shortened
IEnumerable filteredNames =
	   names.Where  (n => n.Length >= 4);

(This example has been further simplified by importing the System.Linq namespace by using the using directive.

LINQ SELECT

Another common query operator is Select, which transforms (or ‘projects’) each element in the a sequence:

//Select example
string[] places = { "hongkong", "singapore", "shanghai" };

	IEnumerable upperPlaces =
	  places.Select (n =>  n.ToUpper());

	foreach (string n in upperPlaces)
	  Console.Write (n + " - ");       // HONGKONG - SINGAPORE - SHANGHAI

As can be seen above Select operates slightly differently than its SQL counterpart, which is primarily used to commence a query and not perform transformations on data.

Anonymous types

Anonymous types are supported in LINQ and a query can project to an anonymous type:

//Anonymous  types LINQ example
	var query = places.Select (n => new {
	                                     Name = n,
	                                     Length = n.Length
	                                   });
	foreach (var row in query)
	  Console.WriteLine (row);

Output:

//Anonymous  types LINQ example output
	{ Name = hongkong, Length = 3 }
	{ Name = singapore, Length = 4 }
	{ Name = shanghai, Length = 5 }

LINQ Take , Skip , Reverse

Elements in an input sequence have an order within LINQ and three basic query operators can use this ordering – Take, Skip and Reverse. Take gets the first x number of elements in a sequence, Skip gets all the elements after skipping x number of elements and Reverse performs a reversal transformation on the elements.

//
	int[] nums = { 1, 2, 3, 4, 5 };

EG – LINQ Take

//Take example
	IEnumerable firstTwo = nums.Take (2);
	// firstTwo = { 1, 2}

EG – LINQ Skip

//Skip example
IEnumerable skipTwo = nums.Skip (2);
	// skipTwo = { 7, 6 }

EG – LINQ Reverse

//Reverse example
	IEnumerable  reverseNums = nums.Reverse() ;
	// reverseNums = { 5, 4, 3, 2, 1 }

LINQ Element operators

Instead of returning a sequence, LINQ can also return a single element in a given sequence. Element operators return a single element from an input sequence. Common element operators are First, Last, ElementAt.

//Element operators example
int[] nums = { 1, 2, 3, 4, 5 };
int lastNum    = nums.Last( );          // 5
int firstNum    = nums.First( );         // 1
int thirdNum  = nums.ElementAt (3);    // 3

LINQ Aggregation operators

These are very similar to their SQL counterparts in that they return a single scalar value of some aggregate of the sequence. The most common aggregation operators in LINQ are Count, Min, Max, and Average:

//Aggregation  operators example
int[] nums = { 1, 2, 3, 4, 5 };

int count     = nums.Count();            // 5
int min       = nums.Min();              // 1
int max       = nums.Max();              // 5
double avg    = nums.Average();          // 3

Count can add conditions for inclusion in the count:

//Count operator example
	int highNums = nums.Count (n =>; 3);   // 3

LINQ Quantifiers

LINQ quantifiers determine a true/false for the given operator and then return a bool . The most common LINQ quantifiers are Contains, Any, All, and SequenceEquals (compares two sequences):

//LINQ Quantifiers example
int[] nums = { 1, 2, 3, 4, 5 };

bool hasNumberSeven = nums.Contains (7);    // false
bool hasSomeElements = nums.Any( );   // true
bool hasOddNums = nums.Any (n => n % 2 == 1);  // true
bool justOddNums = nums.All (n => n % 2 == 1); // false

LINQ  Set operators

LINQ’s set operators accept two input sequences of the same type. Concat appends a sequence to one other,  Intersect returns a sequence representing the intersection of two sequences,  Union returns a sequence representing the union of two sequences, Except returns a sequence representing the difference between two sequences

//Set operators example
int[] sequence1 = { 1, 2, 3 }, sequence2 = { 3, 4, 5 };

	IEnumerable
	  concat = sequence1.Concat (sequence2),   // { 1, 2, 3, 3, 4, 5 }
	  union = sequence1.Union (sequence2),     // { 1, 2, 3, 4, 5 }
 	intersection = sequence1.Intersect (sequence2),   // { 3 }
	  difference1 = sequence1.Except(sequence2),   // { 1, 2 }
Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!