LINQ Extensions

Hi Friends,

In today’s section we’ll see how to use extension methods to achieve the same thing which can be achieved via Comprehension LINQ query.

Below is the code to fetch the same thing via two ways.

I have also created Movies Repository, just to segregate my stuffs here. So, GetMovies() is just fetching all the movies from the repository.

so, now at this point you might be thinking that what i should be using Extension Method or comprehension query. Basically, its a personal choice. If users feel handy with comprehension query, they write comprehension query otherwise extension methods. However, my point is extension methods using lambda expressions generally offer more flexibility over comprehension queries and the general reason for that not all LINQ keywords are exposed to comprehension queries. So, when you are writing extension methods then in that case select operator is optional.

Now, lets see let keyword. let keyword is really important in LINQ queries for persisting some value for later execution like shown below


here, in the movies repository i have modified the name just to execute the query, but that ok that was just done to prove the point. Now, there is one more keyword which is used for grouping or i would say for additional filtering like the example shown below.


below in the snippet i have used group operator to partition my results as shown below.


I have also modified Movie class and Movie Repository

Now, lets suppose you would like to print some additional information like for a particular Genre Id, total count and its collection. So, to do that i’ll extend the query with anonymous syntax as shown below.


Now, lets look at Join query.

for this i have also created one new MovieReview Repo as shown below in the snippet.

so, when i run the same, i will get the below result


I can also go ahead and use LINQ composition like shown below.

For this custom type, i have created the same in my movie repository as shown below in the snippet

Now, when i run the same, it will produce me the below output.


Now, this kind of query is very useful as it increases reusability of the code.

Thanks for joining me.

Happy Coding

2,231 total views, no views today


Hello Friends,

In this section we are going to talk about LINQ TO SQL. Now, Linq to SQL is a simple Object Relationship Mapper(ORM) which means there is equivalent mapping of your class atrributes with Sql server table columns. This works fine with variety of SQL Server technologies. Here, basically our LINQ queries get translated into SQL queries and do the execution down the layer and fetch or commit the data. Then, what i have done is i have added LINQ TO SQL below in my visual studio to visualize my tables as shown below in the diagrams.




Here, we can also see the relationship between Movie and MovieReviews table by clicking on the arrow and checking the properties there. So, here MovieReviews are associated with Movie via foreign key as shown below in the screen shot.


So, with LINQ to SQL, we have also created the data context with which we are going to interact with SQL.


Now, when i start writing my query on the datacontext, it started giving me properties against which i am going to write my query as shown below in the screen shot. Now, this is the significance of ORM. By default, ORM pluralizes your table, but you can override these properties, but thats ok; this is not in the scope of this topic.



so, here the query is fetching best movies based on the average of rating in descending order.


Now, if i hover on the LINQ expression in debugging window, then you can see that LINQ expression got converted into SQL query and this is how it is going to pick the data from db.


and if i simply copy the expression and put the same in the notepad, i can see that it has created the SQL expression as shown below.

one point to note here that LINQ TO SQL is again lazy loader means, it won’t execute the query in the database until it is invoked from a specific call. In this case it is from foreach() statement. This was how LINQ TO SQL works in a nutshell. Thanks for joining me.

Rahul Sahay,
Happy Coding

1,409 total views, no views today

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.


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


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.


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.


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.


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


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


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.

Rahul Sahay
Happy Coding

1,261 total views, 1 views today


Hi Friends,

Today in this section, we’ll see IEnumerable in action and will see that how it actually works and holds true for all collection. As i already said in one of my posts that collection don’t iterate itself, they need enumerators to loop through and its IEnumerable‘s job to provide the enumerators. so, whenever we loop any collection under foreach(), we are actually invoking IEnumarable to get the enumerator. So, IEnumerable exposes only one method and that is GetEnumerators().

Here, enumerator uses three basic properties to iterate in the list and that is MoveNext(),reset and Current. MoveNext() will iterate till the collection ends and Current will set the subsequent item to current. Now, let’s see the same in action.


Now, consider the scenario of foreach(). As shown below in the example foreach() is pretty straight forward, i could have used the same in main method directly as i was using in the previous examples. However, i just wanted to emphasize on one point that foreach() internally replaces the code with with the previous example of IEnumerator.

and offcourse result will be the same only.


Now, there is one exception to this, if the compiler notices that collection which we are iterating through is Array, then it will simply convert the foreach() method to to for loop than IEnumeartor implementation, as this is the most efficient way of iterating through. But, this only holds for arrays.

One more point is, enumeration is read only operation, so if you tries to modify the collection on the fly and iterate through, this won’t allow.


However, the above restriction is not applicable for all the collections. For example, if i change the same to Array and run the again, then compiler won’t complain. However, one point to note that its not a good practice to modify the element while iterating and the reason for this is foreach() for arrays gets converted into for loop, hence modification allowed in that.

Thanks for joining me.

Rahul sahay,
Happy Coding

2,176 total views, 7 views today


Hi Friends,

In this section I’m going to talk about Dictionary implementation. Now, Dictionary is the basic implementation of IDictionary. Before implementing Dictionary, let’s see the below code. This is very straight forward code having a collection printing month name and its short form.


however, in the above snippet i have used List. If i have to make use of Dictionary, then at that point i need to decide one item which can be treated as key. Below, i have made the same code as Dictionary implementation.

Now, when i see the output of this, it will print both key, value pairs in the [] brackets.


Now, if i hover on the var keyword in the foreach() loop, i will come to know that var is converted to name, value pair, hence it output the same.


however, i can get the same result with

but, this is fairly less readable, hence used var keyword, let compiler figure-out what type it is going to be. However, i can use any of the apis if i want to be specific like shown below.


and this will return me only values as shown below.


same thing i can do for Keys as well.

Now, when i have to look up any item in the dictionary then the code will be something like shown below.


However, this code holds true because i know the key because i have written that. How about the dictionary which some body gave you and you are not sure about the key like below, then it will throw the Key not found exception.


For this kind of scenario,we use below snippet. Here, TryGetValue() will look for the key and return the output in a month variable and based on that you can go ahead and print your value.


i can also modify the existing element based on the key as shown in the below snippet. This also proves the point for a given key, only one value can exist in the dictionary.


Now, lets consider a scenario, that you tried printing the value of b. However, in the Dictionary i have the same with B. In that case what will happen, it will return that Key not found. Now, to fix this issue, Dictionary also provides an option to compare the key before fetching. This option comes with interface IEqualityComparer. However, there is already built in string comparer class which compares the string. so, with the below signature it will fetch the value exactly same.


However, i can achieve the same by using interface as well. But, before that lets talk about hash code which is the underlying technology of Dictionary. Now, the way dictionary allocates the key inside in the memory is fairly complicated. Let’s say based on some algorithm they allocate a compartment of memory for a particular Key. Similarly, there can be different compartments for different Keys. However, same algorithm also repeats the compartment for a different key after reaching the threshold. So, a single compartment can have n no of keys. So, if you compare the performance of Dictionary with other collections like List, it is fairly efficient because based on the key it will first identify which compartment i have to look for to fetch the value.

Now, the importance of Hashcode is, dictionary uses hashcode to identify the compartment. Every object has a member function GetHashCode(). This function gets the hashcode of the object. hashcode here is 32bit integer. Now, let’s see whether below snippet works or not.


Now, this failed for a valid reason. so, “b”.GetHashCode()!= “B”.GetHashCode() because both are different strings. Since, b actually don’t exist, hence there is no question of getting same hash code for that. Now, the easiest fix around that is to redirect the hashCode to fetch the orignal one like this.


Now, lets consider a scenario where in want to sort the keys. For that i would use SortedList as shown below in the snippet.

and similarly, i can make the dictionary as readonlydictionary.

However, any attempt to modify the dictionary will give error here.


this was all about Dictionary. Thanks for joining me.

Happy Coding

2,176 total views, no views today

Stack and Queue

Hi Friends,

Now in this section, I am going to talk about Stack. Basically, stack works on the principle of LIFO(Last in First out) means the element which gets inserted in the stack Last will come out first. Here, there are two fundamental principles involved 1)Push and 2)Pop. Push is to insert the element on the stack and Pop to remove the same.

Below, in the snippet i have explained all the basic operations involved with Stack.


Now, lets cover Queue. Queues are opposite of Stack. Queues work on the principle of FIFO(First in First out). Here, also two basic operations are involved to insert(known as Enqueue) and remove(known as Dequeue). Lets see the same in action.


So, this was the stacks and queue. In the next section, will cover some other collection. Till then stay tuned and Happy Coding.

Rahul Sahay
Happy coding

853 total views, 2 views today

Posted in C# | Tagged


Hi Friends,

Today in this section, i am going to talk about Linked Lists. But lets 1st understand Linked Lists here. The purpose of a linked list is to provide a collection where in you can add/remove items very easily. Linked list are having one address section apart from data section as well where in it stores the reference of next node and so on. In case of doubly linked list. on both the ends there are previous and next references of data element, so it can move in the list to and fro.
There are certain features of linked list:-


  • Adding/Removing element is fast.
  • Good at enumeration
  • No index based access to elements.
  • Linked Lists are not very good when it comes for memory consumption.

Now, in the below example I have a linked List code. But, one thing to remember here that with Linked List you can’t use collection initializer to set up values. Below in the screen shot i have highlighted the APIs which Linked Lists offer out of the box.


so, if you see the code then i have missed the month march in the collection. Now, lets suppose if i have to add the same in the collection, then how do we do that. So, for doing the same, what we need to do is go ahead and use the API AddAfter on element as shown below in the snippet. Now, one more point to note here that LinkedList is a collection of LinkedListNode which means i need to find the reference item 1st and then pass the same to the constructor.

then, this will produce the desired output as shown below.


However, one point to note here this is not the efficient way of using LinkedList although AddAfter() is very efficient because in this case we have used Find() method which will scan the entire list until it finds the desired element. But, in this case i had no choice as i didn’t keep the reference stored upfront.Also, one more important point to note here that if Linked List contains the same value more than once in the list, then Find() will only find the 1st one.

Now, for removing the node you can use Remove(“”), but again this is not very efficient as this is going to scan the List. However, you can also directly use RemoveFirst() or RemoveLast() if your intention to remove the item that one or you can pass the reference of that node likewise. So, this was the Linked List. In the next section, we’ll cover some other collection.

Rahul Sahay
Happy Coding

929 total views, 2 views today

Posted in C# | Tagged


Hi Friends,

In today’s discussion, we’ll see how to implement List. So, what is List? To answer this questions, Lists are like Arrays means index based collection + some bonus features like supporting adding and removing the elements from the collection. Below, in the snippet i have array of months containing months till November. However, i attempted to add the December in the collection and found the below error.


Since, arrays are readonly collection, it can’t grow or shrink. Hence, to fix this problem, Lists are introduced. Now, with a minimal change when i go ahead and run the same, then it will produce the expected output.


However, one point to note here that List is a wrapper around array Array[T]. so, when we execute the List code, what we got is newly created list reference with the modified item in it. However, when List got created it always allocates extra blocks of memory to accommodate new incoming request to add the element in the List. Now, there are two main properties associated with List. They are

  • Count:- which gives the total no of elements present in the list.
  • Capacity:- gives the total no of count including extra block of memory to accommodate new ones.

Let’s do a quick demo around this to prove the point.


so, i can go ahead and add upto 16 items to the same list and its capacity won’t change, but, lets suppose that i add one more item to it like shown below, then Lists capacity will get reevaluated and then it will drop the existing internal array and create one new array with capacity 32 as shown below. Remember as i said Lists are wrapper around arrays. So, under the hood arrays are only working to hold the elements.


However, this dynamic allocation of capacity could create performance issue when it comes to recreate the array and reference the same when there millions of item in the list, but if you are roughly sure about the list’s capacity well in advance, then you can use the pass the capacity size as shown below in the snippet.


So, here i passed 20 as capacity, hence it produced the capacity 20 before and after same. Now, lets talk about remove operation. Below in the screen shot, intellisense has listed all the remove options available for the list.


you can use either of the below mentioned option to remove the item. Both of these operations will do the same thing but the later one will be expensive, as it needs to scan all the elements of the list until it finds the required element. However, RemoveAt will simply jump on that index and remove the element. Even after removing the element, list will reorganize internally, so if the removal is the last element of the list, then it will be fastest operation and if the removal of the element is the top element, then it will be the slowest operation.

One more thing here is that you can extend the same to the readonly collection. Now, lets suppose that you want to pass your collection to some other code whom you don’t want this flexibility to modify your List. so, in order to achieve the same you can use the List with readonly collection as shown below.

Now, if i execute the same then it will throw the below exception. One more point to note here, that i am using IList here which means i can get or set the value based on index on the collection being passed.


One point of caution here, even this code can be modified by using reflection. To circumvent we can modify the code a bit like shown below

Now, lets look at another collection and that is Collection. This provides an implementation of IList. Infact this is very similar to readonly collection, only change is you can modify the collection here. However, there is already good implementation of IList is there, then why Collection is required. To answer this question, List is very efficient but it can’t be customized. However, Collection on the other hand is specifically designed to be derived from, hence its highly customizable. Below, in the screen shot, you can see different virtual methods available to get overridden.


so, here i can go ahead and implement any of these and test for specific checks like shown below.


Now, lets look at the ObservableCollection. Now, this is one of the most famous collection to track the changes. As soon as list gets modified, it will send the notification.

Now, when i run the same it will produce me the below output showing that action Add added item December to the collection.


With this i would like to end this List module here only. In the next section, we’ll pick some other module and discuss the same. Till then stay tuned and Happy Coding.

Happy Coding

944 total views, no views today

Posted in C# | Tagged

IEnumerable and ICollection

Hi Friends,

Now, in this section, we are going to talk about two most popular collections and their usages. IEnumerable lets you enumerate the collection. here, it only exposes one member known as GetEnumerator() method. Now, GetEnumerator() returns the enumerator. One important to understand here, that collections don’t iterate itself. It is basically done by enumerator and the sole purpose of IEnumerable is to supply enumerator to the collection. However, foreach works for all the collection. so, if i go ahead and implement the below logic, then also it will produce me the same result.


Now, ICollection declares an object for an in memory collection. However, the basic difference between ICollection and IEnumerable is ICollection is a write opeartion and IEnumerable is a readonly operation only meant for iteration. However, ICollection uses following to modify the collection.

  • Add()
  • Remove()
  • Clear()
  • IsReadOnly

Apart from this it also gives count of the collection and checks for containing element with contains(). Now, let me go ahead and discuss these properties one by one. In the below snippet, i have used the count property of the collection. Apart from that you can use other properties as well as shown below in the screen shot.



However, for Lists we can directly get the count by using count property on the variable and by using length on the array variable. But, the intention was to show the Collection properties here. Now, lets look at this implementation. This is explicit casting.

and if i see the output of this then it will produce the following result.


and the reason for this is that Arrays are readonly collection.

One more interface we is IReadonlyCollection. Now, this property is enumerable and also tells that how many elements it has. Another important interface is IList. Here, in this case elements can be accessed based on its index like string march = monthsofyear[2]; IList is also implemented by Arrays and Lists.

We’ll discuss all these interfaces and its imlementation in the coming sections. Till then stay tuned and happy coding.

Happy Coding

1,050 total views, no views today

Posted in C# | Tagged

C# Collection – Array 2nd Part

Hi Friends,

Now in this section, we are going to delve inside the arrays. 1st thing which i am going to do here is equality check. so, if you look at the below code you will find, it is comparing two elements and it’s returning for the same value true for 1st case and false for 2nd case. Now, reason for the same is because its comparing the references not the value. and this logic applies not only to arrays rather to all Microsoft Collections.


so, it means all arrays are derived from system.object types and we can prove the same with a small illustration.


One more important point with arrays is you can any time cast array of derived type to array of base type like shown below in the example. This is also known as array covariance.


Arrays also providing copying array to a different array, here we can use either copyTo or Copy method to achieve the same. Below, in the example i have used copyTo method to copy the array to a new array starting at a specific index. also, in the output i have also compared the two arrays just to prove the point that these arrays are pointing to different locations.


However, to achieve the same there is much cleaner an simpler which LINQ extension provides us and that is ToArray() as well. Now, let’s see ordering of Arrays. .Net also provides flexibility to reverse the array and sort the same in some order. Both methods are overloaded and static which means the array which you want to sort or reverse you need to pass the same as a parameter.


However, i can achieve the same using LINQ extension, but if i do

then it won’t reverse the array rather it will create a new object of IEnumerable. However, Linq reverse expects a variable like shown below.


with one small change it will work as expected.


In the above snippet, i have extended the same linq to copy the array to destination. This is one of the efficient ways of doing the same. However, if i need to sort the same then i will use the sort method as shown below in the snippet. This will sort alphabetically.


However, this results true for those collections which are sortable by nature means array of nos, strings etc…how about sorting those which are of type T. In this case to rescue us IComparer comes into picture. so, let’s suppose a scenario i need to sort the months of the year by the length of month. Now, to do the same i need to write one comparer as shown below


let’s consider a scenario where in your input type is very big let’s suppose an array of million items, and you have to find one element out of that. well most efficient way is to examine the different sorting algos and implement the fastest one. However, there is one which we can use easily is BinarySearch algorithm. This is in built. However, there is one catch with binary search, it expects input order in sorter order. so, my implementation will be something like below.

and it will produce the below output.


With this i would like to finish Arrays implementation. In the next section, we’ll see some other collection and its usage, till then stay tuned and Happy Coding.


1,265 total views, no views today

Posted in C# | Tagged