Language Integrated Query (LINQ) is one of the integral part of
C# which was introduced in Visual Studio 2008. LINQ is
fast, easy to
learn, easy to
understand and support various different data sources such as SQL, ADO.Net, Entity Framework, XML and all .Net Collections.
All the methods written in LINQ are written as
Extension methods which are directly or indirectly members of
IEnumerable interface, which means any data source type or class which is of type
IEnumerable or which implements
IEnumerable interface can use the extension method which is used in LINQ to perform query operations.
LINQ can be written in two way
Query Syntax (SQL like syntax)
Method Syntax (Lambda expression)
There is no performance difference between Query and method syntax while using them, but
Microsoft strongly recommends to use Query Syntax as opposed to method Syntax, since Query Syntax will be very neat and readable and looks very similar to SQL queries.
But anyways, while your LINQ Query syntax is executed, compiler is anyways going to turn the Query syntax to its equivalent method syntax and then going to perform the intended operation upon that.
In all upcoming article we will discuss LINQ using both Query Syntax and Method Syntax and see how they behave.
In all upcoming articles we are going to discuss from the very basic operations to most commonly used complex operation done in Collections, SQL and XML data source.
Lets write a very simple code using List of string to perform operations such
- Selecting names which contains char “a”
- Ascending order of names
public static void SimpleStringOperationWithLINQ()
{
//Declare List of strings
List names = new List { "Karthik", "John", "Automation", "Execute", "Selenium", "Robotium" };
// Select all strings which contains char "a"
// USING QUERY SYNTAX
IEnumerable result = from name in names
where name.Contains("a")
select name;
foreach (string item in result)
{
Console.WriteLine(item);
}
Console.WriteLine("\n");
//USING METHOD SYNTAX
IEnumerable result1 = names.Where(x => x.Contains("a")).Select(x => x);
foreach (string item in result1)
{
Console.WriteLine(item);
}
Console.WriteLine("\n");
//Ascending order Names
// USING QUERY SYNTAX
IEnumerable aresult = from name in names
orderby name ascending
select name;
foreach (string item in aresult)
{
Console.WriteLine(item);
}
Console.WriteLine("\n");
// USING METHOD SYNTAX
IEnumerable aresult1 = names.OrderBy(x => x);
foreach (string item in aresult1)
{
Console.WriteLine(item);
}
Console.WriteLine("\n");
}
While executing the code, the output looks like this
In this series of LINQ, we are going to discuss more and more about how LINQ can be used with various different data sources (not just Collections) and how to utilize the power of LINQ.
I hope you like the start, please leave your comments.
Thanks,
Karthik KK