Here we discuss about how many ways we can write LINQ query in .Net. There are two different ways available in .Net to write LINQ query.Those are
I will explain about each type with example. For example you have string array, I will show you how to write LINQ query by using query syntax and method syntax on that string array
Query syntax:
string[] arrNames = { "John", "Smith", "Dennies", "Bob" };
IEnumerable<string> names = from fn in arrNames
where fn.StartsWith("S")
select fn;
foreach (string name in names)
{
Console.WriteLine(name);
}
Console.ReadLine();
As shown above you will write the LINQ query on array data source to find the names which start with “S”.
Method Syntax:
string[] arrNames = { "John", "Smith", "Dennies", "Bob" };
IEnumerable<string> names = arrNames.Where(fn => fn.StartsWith("S"));
foreach (string name in names)
{
Console.WriteLine(name);
}
Console.ReadLine();
In the above we used the method syntax to write the LINQ query to find the names from array data source which start with “S”. Notice that the query using method syntax accepts lambda expressions for its Where() and Select() methods.
query syntax:
IEnumerable<string> names = from fn in arrNames
where fn.StartsWith("S")
select fn;
method syntax:
IEnumerable<string> names = arrNames.Where(fn => fn.StartsWith("S"));
Query syntax and Method syntax are identical other than syntax difference. Query syntax uses language-specific syntax (C# or VB.NET) and Method syntax is language independent. Query syntax is a subset of method syntax. And method syntax gives better performance as compared with query syntax because all the query syntax statements get translated by the compiler into method syntax.