C# Query Expression is an expression that is written by using LINQ query syntax. The LINQ (Language Integrated Query) is a language that is used to construct a query.
C# Query Expression contains set of clauses and use query expression similar to SQL.
Query expression must start with from clause and end with a select or group clause.
To store the query, we must use IEnumerable type variable. It provides a IEnumerator.MoveNext method to iterate elements.
We can iterate elements from the IEnumerable sequence by using two ways.
- IEnumerator.MoveNext method
- foreach loop
Note: We must use System.Linq namespace to execute query expression.
Let's see an example that displays odd numbers from the array by using the expression query.
C# Query Expression Example 1
using System;
using System.Linq;
using System.Collections.Generic;
namespace CSharpFeatures
{
class DelegateInference
{
static void Main(string[] args)
{
int[] IntVal = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Query Expression
IEnumerable<int> OddVal =
from val in IntVal
where (val % 2) != 0
select val;
// Iterating fetched result
foreach (int val in OddVal)
{
Console.WriteLine(val);
}
}
}
}
Output
1
3
5
7
9
C# Query Expression Example 2
In this example, we are using query expression to fetch student name from the collection of students.
using System;
using System.Linq;
using System.Collections.Generic;
namespace CSharpFeatures
{
class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public static List<Student> GetStudents()
{
List<Student> student = new List<Student>();
Student student1 = new Student { ID = 101, Name = "Irfan", Email = "irfan@gmail.com"};
Student student2 = new Student { ID = 102, Name = "Rahul", Email = "rahul@abc.com" };
Student student3 = new Student { ID = 103, Name = "John", Email = "john@abc.com" };
student.Add(student1);
student.Add(student2);
student.Add(student3);
return student;
}
}
class QueryExpressionExample
{
static void Main(string[] args)
{
IEnumerable<string> queryName =
from student in Student.GetStudents()
where student.ID == 103
select student.Name;
foreach (var s in queryName)
Console.Write(s);
}
}
}
It displays a student, having student id 103.
Output