LINQ Pocket Reference: Snippet 1 May 6, 2009
Posted by webchetan in Uncategorized.trackback
LINQ or Language Integrated Query allows you to write structures type safe-queries over local object collections and remote data sources. Introduced in .NET 3.5, it (LINQ) lets you query any collection implementing IEnumerable<>, whether an array, list, XML DOM, or remote data source.
LINQ offers the benefits of both compile-time type checking and dynamic query composition.
Base units of LINQ are sequences and elements.
A sequence is any object that implements the IEnumerable<> interface. Now the element is each item in the sequence.
Ex:
string[] names = { “Apples”, “Oranges”, “Grapes” };
Such a sequence is called a local sequence, because it represents a local collection of objects in memory.
A query operator is a method that transforms a sequence.
A query is an expression that transforms sequences with query operators. For instance we can apply the ‘Where’ operator on a simple array to extract those whose length is at least 7 characters long.
Ex:
string[] names = { “Apples”, “Oranges”, “Grapes” };
IEnumerable<string> filteredNames = System.Linq.Enumerable.Where (names, n => n.length >= 7);
foreach (string n in filteredNames) { Console.Write (n + “|”); }
Output: Oranges
The above data and examples are courtesy of LINQ Pocket Reference by Joseph Albahari and Ben Albahari @ O’Reilly ®
More snippets to follow soon, along with working examples and links.
Comments»
No comments yet — be the first.