LINQ Query Syntax
LINQ Query Syntax
There are two basic ways to write a LINQ query to IEnumerable collection or IQueryable data sources.
Query Syntax
Query syntax is similar to SQL (Structured Query Language) for the database. It is defined within the C# or VB
code.
The LINQ query syntax starts with from keyword and ends with select keyword. The following is a sample LINQ
query that returns a collection of strings which contains a word "Tutorials".
// string collection
IList<string> stringList = new List<string>() {
"C# Tutorials",
"VB.NET Tutorials",
"Learn C++",
"MVC Tutorials" ,
"Java"
};
Try it
After the From clause, you can use different Standard Query Operators to filter, group, join elements of the
collection. There are around 50 Standard Query Operators available in LINQ. In the above figure, we have used
"where" operator (aka clause) followed by a condition. This condition is generally expressed using lambda
expression.
LINQ query syntax always ends with a Select or Group clause. The Select clause is used to shape the data. You
can select the whole object as it is or only some properties of it. In the above example, we selected the each
resulted string elements.
In the following example, we use LINQ query syntax to find out teenager students from the Student collection
(sequence).
// Student collection
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 }
};
Try it
// Student collection
Dim studentList = New List(Of Student) From {
New Student() With {.StudentID = 1, .StudentName = "John", .Age = 13},
New Student() With {.StudentID = 2, .StudentName = "Moin", .Age = 21},
New Student() With {.StudentID = 3, .StudentName = "Bill", .Age = 18},
New Student() With {.StudentID = 4, .StudentName = "Ram", .Age = 20},
New Student() With {.StudentID = 5, .StudentName = "Ron", .Age = 15}
}
Try it
Points to Remember :
1) As name suggest, Query Syntax is same like SQL (Structure Query Language) syntax.
2) Query Syntax starts with from clause and can be end with Select or GroupBy clause.
3) Use various other opertors like filtering, joining, grouping, sorting operators to construct the desired result.
4) Implicitly typed variable - var can be used to hold the result of the LINQ query.
Share Tweet Share Whatsapp
Previous Next
TUTORIALSTEACHER.COM TUTORIALS
LINQ Sass
[email protected]
E-MAIL LIST
Subscribe to TutorialsTeacher email list and get latest updates, tips & tricks on C#, .Net, JavaScript, jQuery, AngularJS, Node.js to your
inbox.
Email address GO
HOME PRIVACY POLICY TERMS OF USE ADVERTISE WITH US 2020 TutorialsTeacher.com. All Rights Reserved.