1. from clause: This is used to specify the iteration variable name. This acts as alias name for the data source.
2. in clause: This is used to specify the main data source for the query.
3. let clause (optional): This is used to declare any identifier with a value, that is to be used during the query execution.
4. where clause (optional): This is most frequently used optional clause, using which you can specify the condition in the query.
5. orderby clause (optional): This is used to specify the sorting expression if required.
6. select clause: This is used to specify the object, which is required in the query results.
7. group (optional): This is similar to “group by” clause in SQL. This retrieves grouped data.
Note: The result of a LINQ query, should be assigned into a variant type variable. (“var” type).
LINQ to Objects
namespace LINQtoObjectsDemo
{
class Student
{
public int StudentID;
public string Name;
public string Course;
public int Marks;
public Student(int StudentID, string Name, string Course, int Marks)
{
this.StudentID = StudentID;
this.Name = Name;
this.Course = Course;
this.Marks = Marks;
}
}
class Program
{
static void Main(string[] args)
{
//data source
Student[] stu = { new Student(101, "Prakash", "MBA", 765),
new Student(102, "Pradeep", "MBA", 471),
new Student(103, "Pushpa", "Msc", 590),
new Student(104, "Purna", "MCA", 223),
new Student(105, "Purnima", "MCA", 450)};
//linq query with where clause
var query1 = from s in stu where s.Course == "MCA" select s;
Console.WriteLine("MCA Students:");
foreach (var q in query1)
Console.WriteLine(q.StudentID + ", " + q.Name + ", " + q.Course + ", " + q.Marks);
//linq query with let and where clauses
var query2 = from s in stu let avg=s.Marks/10 where avg<35 select s;
Console.WriteLine("\nFailed Students:");
foreach (var q in query2)
Console.WriteLine(q.StudentID + ", " + q.Name + ", " + q.Course + ", " + q.Marks);
//linq query with orderby clause
var query3 = from s in stu orderby s.Marks select s;
Console.WriteLine("\nStudents (sort on marks):");
foreach (var q in query3)
Console.WriteLine(q.StudentID + ", " + q.Name + ", " + q.Course + ", " + q.Marks);
//linq query with orderby clause (descending)
var query4 = from s in stu orderby s.Marks descending select s;
Console.WriteLine("\nStudents (sort on marks - descending):");
foreach (var q in query4)
Console.WriteLine(q.StudentID + ", " + q.Name + ", " + q.Course + ", " + q.Marks);
//linq query with group clause
var query5 = from s in stu group s by s.Course;
Console.WriteLine("\nStudents with grouping:");
foreach (var p in query5)
{
Console.WriteLine(p.Key + ":");
foreach (var q in p)
Console.WriteLine(" " + q.StudentID + ", " + q.Name + ", " + q.Course + ", " + q.Marks);
}
Console.Read();
}
}
}