Getting started with LINQ

Hi Friends,

In today’s section, we are going to talk about LINQ and its capabilities. Now, LINQ is something which gives you out of the box querying facility in statically typed language itself means in C# itself. Let’s see some of the examples in action. Below, I have created one simple movie class with few properties in it.

however, when i am writing the query in the main program, you can see that intellisense is giving me all the properties which i have created above.

46th

when i execute the same, it prints the below value.

47th

However, there are around 50 standard operators provided by microsoft to query the things. You can check each implementation on MSDN as well. Also, LINQ is designed in such a way that it supports all kind of extensibility like you can write LINQ to LDAP, Amazon, Flicker or you can write your own custom operators as well.

However, we can also go ahead and use LINQ to query objects like shown in the below snippet

so, it produced me the Movie type as public type.

48th

Deferred Execution is again one of the most crucial part of LINQ operations means we can have the query defined, but until we invoke it that query part is not going to be executed. Consider the below example where in i am adding a new movie to list and then invoking the query from the foreach() operation. So, in the final result it will print me the expected value as shown below.

49th

I can also use LINQ to query XML like shown below. So, here i have constructed one xdocument on the fly of processes and querying the same via LINQ.

51th

then, i can see the result in the debugging visualizer as shown below.

50th

Now, since the document is constructed i can go ahead query the document as well as shown below in the snippet.

52nd

This was the brief introduction of using LINQ with variety of instances. we’ll delve further inside this in the coming sections. Till then stay tuned and Happy Coding.

Thanks,
Rahul Sahay
Happy Coding