.NET Language Integrated Query (LINQ)

Language Integrated Query, or LINQ, integrates query syntax inside the C# language. Accessing different sources is possible using the same syntax.

Some examples using arrays as the data source:

using System;
using System.Linq;

class LinqExample
{
	static void Main()
	{
		string[] products = { "kiwi", "almond", "banana", "apple", "grapefruit", "orange", "cucumber", "papaya", "apricot", "grapes" };
		var prodQuery = from p in products
					where p.StartsWith("a")
					orderby p ascending
					select p;
		Console.WriteLine("\r\nPRODUCTS:");
		foreach (string s in prodQuery)
		{
			Console.WriteLine(s);
		}
	}
}
using System;
using System.Linq;

class LinqExample
{
	static void Main()
	{
		int[] nums = { 9, 2, 3, 7, 1, 0, 8, 5, 4, 6 };
		var numQuery = from n in nums
						where n >= 3 && n <= 7
						orderby n ascending
						select n;
		Console.WriteLine("\r\nNUMBERS:");
		foreach (int i in numQuery)
		{
			Console.WriteLine(i.ToString());
		}
	}
}

The below statement is a LINQ query. The clauses from, where, orderby, ascending, descending, and select are keywords.

var numQuery = from n in nums
				 where n >= 3 && n <= 7
				 orderby n ascending
				 select n;

A LINQ example using a List:

using System;
using System.Collections.Generic;
using System.Linq;

class LinqExample
{
	static void Main()
	{
		List<string> names = new List<string> { "Xavier", "John", "David", "Jack", "Aaron" };
		var namQuery = from n in names
						where n.StartsWith("J")
						orderby n ascending
						select n;
		Console.WriteLine("\r\nNAMES: (first iteration)");
		foreach (string s in namQuery)
		{
			Console.WriteLine(s);
		}

		names.Add("Jill");
		names.Add("Edward");
		Console.WriteLine("\r\nNAMES: (second iteration)");
		foreach (string s in namQuery)
		{
			Console.WriteLine(s);
		}
	}
}
NAMES: (first iteration)
Jack
John

NAMES: (second iteration)
Jack
Jill
John
<< < [Page 1 of 7] > >>