Language Integrated Query (LINQ) provides a set of operators called as standard query operators for simplifying data access and manipulation across data sources.
The standard query operator is a set of methods. These methods operate on sequences. A sequence is an object whose type implements either the IEnumerable
Related Articles
- Language Integrated Query (LINQ) tutorials for beginners
Query Operators - SQL vs LINQ
Following table shows the operators based on the functionality and also corresponding SQL operators.
Functionality | SQL Operators | LINQ Operators |
---|---|---|
Projection | Select | Select SelectMany |
Restriction | Where | Where |
Ordering | OrderBy | OrderBy ThenBy |
Grouping | GroupBy | GroupBy |
Quantifiers | Any All | Any All |
Partioning | Not available | Take Skip TakeWhile SkipWhile |
Sets | Distinct Union Intersect | Distinct Union Intersect Except |
Elements | Not available | First FirstOrDefault ElementAt |
Aggregation | Count Sum Min Max Average | Count Sum Min Max Average |
Writing Query – SQL vs LINQ
Examples
Display the names and phone numbers of all customers residing in Mumbai city.
SQL Syntax
LINQ Syntax
The following code example demonstrates how the standard query operators can be used to obtain information about a sequence.
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);
}
/*output:
Words of length 3:
THE
FOX
THE
DOG
Words of length 4:
OVER
LAZY
Words of length 5:
QUICK
BROWN
JUMPS
*/