Database Management
Register
Advertisement

The .NET Language-Integrated Query defines a set of general purpose standard query operators that allow traversal, filter, and projection operations to be expressed in a direct yet declarative way in any .NET-based programming language.

These standard query operators will allow queries to run against any IEnumerable datatype. LINQ allows third parties to set up the use of these standard query operators with new domain-specific operators that are appropriate for the target domain or technology. More importantly, Microsoft says, third parties are also free to replace the standard query operators with their own implementations that provide additional services such as remote evaluation, query translation, optimization, and so on. Because LINQ uses all the same standard query operators, if it is implemented correctly will have the same support as the standard query operators.

Microsoft uses the term language-integrated query to "indicate that query is an integrated feature of the developer's primary programming languages (for example, Visual C#, Visual Basic). Language-integrated query allows query expressions to benefit from the rich metadata, compile-time syntax checking, static typing and IntelliSense that was previously available only to imperative code. Language-integrated query also allows a single general purpose declarative query facility to be applied to all in-memory information, not just information from external sources."

Reference:"LINQ: .NET Language-Integrated Query"."http://msdn.microsoft.com/en-us/library/bb308959.aspx". Microsoft. Retrieved on 2008-10-26.

Cc163400.fig01 L(en-us) [1]

Humble Beginings:[]

It started out as a humble Visual Studio project on my desktop machine way back in the fall of 2003, long before anyone heard about it, long before anyone even guessed what would come next, except for the readers of this blog, of course, since I used to post often with long obtuse and sometimes psychedelic meanderings that with the proper one-time pad to decrypt it you might have possibly guessed what was on my mind. I needed that project to prepare for what was coming. I needed expression trees and a basic SQL translator to get ready for the day when I would get my hands on the C# codebase and turn it into language that could actually do something interesting for a change; a language that would know how to query. To read more from Matt Wayward visit [2]....


List of available operators:[]

Select / SelectMany Further information: Map (higher-order function) The Select statement is used to perform a projection on the collection to select either all the data members that make up the object or a subset of it. The SelectMany operator is used to perform a one-to-many projection, i.e., if the objects in the collection contain another collection as a data member, SelectMany can be used to select the entire sub-collection. The user supplies a function, as a delegate, which projects the data members. Selection creates an object of a different type, which has either same or as many data members as the original class. The class must be already defined for the code to be compilable.

Where Further information: Filter (higher-order function) The Where operator allows the definition of a set of predicate rules which are evaluated for each object in the collection, and objects which do not match the rule are filtered away. The predicate is supplied to the operator as a delegate.

Sum / Min / Max / Average / Aggregate Further information: Fold (higher-order function) These operators take a predicate that retrieves a certain numeric value from each element in the collection and uses it to find the sum, minimum, maximum, average or aggregate values of all the elements in the collection, respectively.

Join / GroupJoin The Join operator performs an inner join on two collections, based on matching keys for objects in each collection. It takes two functions as delegates, one for each collection, that it executes on each object in the collection to extract the key from the object. It also takes another delegate via which the user specifies which data elements, from the two matched elements, should be used to create the resultant object. The GroupJoin operator is used to perform a group join. Like the Select operator, the results of a join are instantiations of a different class, with all the data members of both the types of the source objects, or a subset of them.

Take / TakeWhile The Take operator is used to select the first n objects from a collection, while the TakeWhile operator, which takes a predicate, selects those objects which match the predicate.

Skip / SkipWhile The Skip and SkipWhile operators are complements of Take and TakeWhile - they skip the first n objects from a collection, or those objects which match a predicate (for the case of SkipWhile).

OfType The OfType operator is used to select the elements of a certain type.

Concat The Concat operator concatenates two collections.

OrderBy / ThenBy The OrderBy operator is used to specify the primary sort ordering of the elements in a collection according to some key. The default ordering is in ascending order, to reverse the order the OrderByDescending operator is to be used. ThenBy and ThenByDescending specifies subsequent ordering of the elements. The function to extract the key value from the object is specified by the user as a delegate.

Reverse The Reverse operator reverses a collection.

GroupBy The GroupBy operator takes a delegate that extracts a key value and returns a collection of IGrouping<Key, Values> objects, for each distinct key value. The IGrouping objects can then be used to enumerate all the objects for a particular key value.

Distinct The Distinct operator removes duplicate instances of a key value from a collection. The function to retrieve the key value is to be supplied as a delegate.

Union / Intersect / Except These operators are used to perform a union, intersection and difference operation on two sequences, respectively.

EqualAll The EqualAll operator checks if all elements in two collections are equal.

First / FirstOrDefault / Last / LastOrDefault These operators take a predicate. The First operator returns the first element for which the predicate yields true or throws an exception if nothing matches. The FirstOrDefault operator is like the First operator except that it returns the default value for the element type (usually a null reference) in case nothing matches the predicate. The last operator retrieves the last element to match the predicate, or throws an exception in case nothing matches. The LastOrDefault returns the default element value if nothing matches.

Single The Single operator takes a predicate and returns the element which matches the predicate. An exception is thrown if none or more than one elements match the predicate.

ElementAt The ElementAt operator retrieves the element at a given index in the collection.

Any / All / Contains The Any operator checks if there are any element in the collection matching the predicate. It does not select the element, but returns true for a match. The All operator checks if all elements match the predicate. The Contains operator checks if the collection contains a given value.

Count The Count operator counts the number of elements in the given collection.

Reference:"Standard Query Operators"."http://download.microsoft.com/download/5/8/6/5868081c-68aa-40de-9a45-a3803d8134b8/standard_query_operators.doc". Microsoft. Retrieved on 2008-10-26.



LINQ Samples[]

Restriction Operator[]

Where

This sample prints each element of an input integer array whose value is less than 5. The sample uses a query expression to create a new sequence of integers and then iterates over each element in the sequence, printing its value.

public void Linq1() {

    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };


    var lowNums =

        from n in numbers

        where n < 5

        select n;


    Console.WriteLine("Numbers < 5:");

    foreach (var x in lowNums) {

        Console.WriteLine(x);

    }

}

Result

Numbers < 5:
4
1
3
20

Grouping Operator[]

GroupBy

This sample uses group by to partition a list of numbers by their remainder when divided by 5.

public void Linq40() { 

           int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

                        var numberGroups =

                           from n in numbers

                          group n by n % 5 into g

                          select new { Remainder = g.Key, Numbers = g };


                      foreach (var g in numberGroups) { 

                        Console.WriteLine("Numbers with a remainder of {0} when divided by 5:", g.Remainder);

                        foreach (var n in g.Numbers) {

                                Console.WriteLine(n);

                         }       

                       }

}



Result

Numbers with a remainder of 0 when divided by 5:
 5
 0 
Numbers with a remainder of 4 when divided by 5:
 4
 9 
Numbers with a remainder of 1 when divided by 5:
 1
 6 
Numbers with a remainder of 3 when divided by 5:
 3
 8 
Numbers with a remainder of 2 when divided by 5:
 7 
 2

Projection Operator[]

Select

his sample prints a sequence of integers one greater than those in an input array. The sample uses the expression in the select clause to add one to each element in the new sequence.

public void Linq6() {    

int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

    var numsPlusOne =

        from n in numbers

        select n + 1;


        Console.WriteLine("Numbers + 1:");

        foreach (var i in numsPlusOne) {  

        Console.WriteLine(i);    }}


Result

Numbers + 1:
6
5
2
4
10
9
7
8
31

Ordering Operators[]

OrderBy

This sample prints an alphabetically sorted version of an input string array. The sample uses orderby to perform the sort.

publicvoid Linq28() {
    string[] words = {"cherry", "apple", "blueberry" };
        
    var sortedWords =
        from w in words
        orderby w
        select w;

        Console.WriteLine("The sorted list of words:");
    foreach (var w in sortedWords) {
        Console.WriteLine(w);
    }
}

Result

 The sorted list of words:
apple
blueberry
cherry

Examples[]

LINQ to SQL '5 Minute Overview': http://www.hookedonlinq.com/LINQtoSQL5MinuteOverview.ashx

LINQ to Datasets: http://www.hookedonlinq.com/LINQtoDatasets.ashx

LINQ to Google http://www.codeplex.com/glinq

LINQ with PHP Implementation: http://www.codeplex.com/PHPLinq


Bibliography[]

MSDN, . (2009). 101 linq samples. Retrieved from http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

Advertisement