Query Operator
- query operators are the methods that form the LINQ patterns.
- In simple terms query operators are nothing but methods that operate on an object whose type implements the IEnumerable<T> interface or the IQueryable<T> interface. For example Select(), Where(), GroupBy(), ToList(), ToArray()..etc.
- These Query Operators are defined using Extension methods
- Based on the Query Operators used in the LINQ the timing of their execution differs, that is depending on whether they return a singleton value(Immediate Execution) or a sequence of values(Deferred Execution).
Query Expression Syntax
- A query expression is a more readable form of expressing a query than its query operators equivalent.
- Example
string sentence = "the quick brown fox jumps over the lazy dog";
// Split the string into individual words to create a collection.
string[] words = sentence.Split(' ');
// Using query expression syntax.
var query = from word in words
group word.ToUpper() by word.Length into gr
orderby gr.Key
select new { Length = gr.Key, Words = gr };
// Using method-based query syntax.
var query2 = words.
GroupBy(w => w.Length, w => w.ToUpper()).
Select(g => new { Length = g.Key, Words = g }).
OrderBy(o => o.Length);
foreach (var obj in query)
{
Console.WriteLine("Words of length {0}:", obj.Length);
foreach (string word in obj.Words)
Console.WriteLine(word);
}
// This code example produces the following output:
//
// Words of length 3:
// THE
// FOX
// THE
// DOG
// Words of length 4:
// OVER
// LAZY
// Words of length 5:
// QUICK
// BROWN
// JUMPS
Deferred Execution Types
- Deferred Execution can be further sub-divided into two types based on the Query Operators used(when more than one data source used)
- Streaming
- Streaming operators do not have to read all the source data before they yield elements.
- At the time of execution, a streaming operator performs its operation on each source element as it is read and yields the element if appropriate.
- A streaming operator continues to read source elements until a result element can be produced. This means that more than one source element might be read to produce one result element.
- Non-Streaming
- Non-streaming operators must read all the source data before they can yield a result element. Operations such as sorting or grouping fall into this category.
- At the time of execution, non-streaming query operators read all the source data, put it into a data structure, perform the operation, and yield the resulting elements.
No comments:
Post a Comment