- Linq Syntax and Query
- How to write Linq Query
- Query Syntax and Method Syntax
- Query Syntax
- Method Syntax
Query Syntax
Query Syntax is easy to learn. It has SQL like query syntax but it does not support all query operators in LINQ. Method Syntax is the more powerful way to write LINQ queries and it is also a standard way to write LINQ syntax.
DefineFrom <range variable> in <IEnumerable<T> or IQueryable<t> collection> <standard query operators> <lambda expression> <select or groupBy operator> <result formation>
Programming Example 1
In this example, I am going to create a simple product list and then access all the items using the LINQ query. This is a simple console example.
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqExample
{
class Program
{
static void Main(string[] args)
{
// Creating List
IList<string> productList = new List<string>()
{
"Hard Disk",
"Monitor",
"SSD Disk",
"RAM",
"Processor",
"Bluetooth",
"Keyboard & Mouse"
};
var result = from s in productList
select s;
foreach(string str in result)
{
Console.WriteLine(str.ToString());
}
Console.ReadKey();
}
}
}
Output
Hard Disk
Monitor
SSD Disk
RAM
Processor
Bluetooth
Keyboard & Mouse
_
Programming Example 2: Filtering Result
In the previous example, you executed your first LINQ query that returned all the item from the list. In this example, we will move one step forward and filter result using where clause.
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqExample
{
class Program
{
static void Main(string[] args)
{
// Creating List
IList<string> productList = new List<string>()
{
"Hard Disk",
"Monitor",
"SSD Disk",
"RAM",
"Processor",
"Bluetooth",
"Keyboard & Mouse"
};
var result = from s in productList
where s.Contains("Disk")
select s;
foreach(string str in result)
{
Console.WriteLine(str.ToString());
}
Console.ReadKey();
}
}
}
Output:
Hard Disk
SSD Disk
_
Summary
If you have executed program successfully then congratulations because you have crossed half way of LINQ. Once you know how to write LINQ syntax, it becomes very easy to learn LINQ methods and extensions. This chapter teaches you LINQ Query Syntax and in the next chapter, you will learn LINQ Method Syntax.