March 2008 - Posts
Select operator is one of the projection operator available in LINQ. Select operator allows you to return an output sequence of certain type by transforming the input sequence using the lambda expression. The output sequence could be of same element type or different but the number of elements returned from the Select operator is always same as the number of elements passed in the input sequence.
The prototype of the select operator looks like this
public static IEnumerable<S> Select<T,S>
(this IEnumerable<T> source,Fund<T,S> selector);
The above extension method is applicable to any object implementing IEnumerable<T>. The select operator is passed in a delegate that enumerates the input sequence of T and returns an output sequence that consists of elements of type S. As discussed earlier T and S could be same type.
public static IEnumerable<S> Select<T,S>
(this IEnumerable<T> source,Fund<T,int,S> selector);
The second prototype shown above is not much different from the first prototype except the predicate takes an additional integer argument which identifies the index of the element in the input sequence.
Let's look through few examples of how we can use select operator in linq to sql, linq to xml and linq to objects.


In the above example you would notice I am using the select operator in query syntax to retrieve person whose first name starts with Mike and i am selecting the entire object. If all i want is to retrieve is the first name, I can make use of anonymous type to select only the first name property. This is how you would do it.

From the above example, we are creating an anonymous type on the fly which consists of one property called FN that we are assigning using the FirstName property on the person object. Another point worth mentioning is when you are returning anonymous types in the projection, you have to use the var keyword to assign the result to the variable. The reason for this is because, you do not know what is the actual type of the anonymous class is. When you use var keyword, the compiler infers the infers the type from the results.
You can write the same query using method syntax as follows.

In the above code, we are using method syntax to achieve the same results. Also notice that the output sequence is not of the same type as the input sequence. Input sequence is a collection of Person and the output sequence is of type string.
Notice in the above code we are returning the length of the lastName property as integer. This demonstrates that the output sequence does not necessary has to be the same type as the input sequence.
Let's look at example of select operator with predicate containing index of the element.
In the above code, we are making use of the indexer and assigning it to the Position property of the anonymous type. The result as you can see from the output is displaying the index and the Name.
So far we have only looked at examples that made use of select operator in linq to objects, select operator can also be used to select data from xml file or xml string.

This time we are making use of the select operator with xml data. We convert xml data into our predefined objects. by casting the element to right type and assigning it to the appropriate property on our objects.
Not only can you use select operator to convert xml data to objects but you can convert objects to xml by making use of select operator. Let's take a look at an example of that.
_thumb.png)
In the code above I make use of the select to create xml elements from a collection of person objects in memory. We then output the result of xml to the console.
Not only can you use select operator with xml but you can also use select operator on .net classes.

In the above got we are making use of the select operator to only get name of the directories found on C drive.
You can also use select operator to create nested collections and transform the original hierarchy into a completely new one that meets your needs. Let's look at an example of that.

In the above example we have nested collections making use of nested select statements.In the first select statement we grab the name of the contact and its total order count. We then create a nested collection on the fly from a nested query that creates a collection of orders consisting of orderid and orderdate.
Where operator is a restriction operator that allows you to filter collection of objects if the collection implements IEnumerable. If the collection happens to implement IQueryable, where operator gets translated to equivalent SQL server operator and the filter gets applied on SQL server. When using where operator you provide a Func delegate that returns the element if it matches the condition passed in as a lambda expression.
public static IEnumerable<T> Where<T>(
this IEnumerable<T> source,
Func<T, bool> predicate);
Above code represents the prototype for the Where operator. Looking at the prototype, we can see that it is an extension that is visible to any object that implements IEnumerable<T>. The second argument to the where operator takes in a predicate that gets applied on every element being iterated in the collection. Only when the predicate returns a value of true does the element gets counted as being part of returned sequence. The predicate takes an argument of T which is the type of element source collection consists of. When you are applying a where clause the number of elements can never be more then the source collection and the objects are not transformed in any form or fashion.
The second prototype for the where operator looks like this
The Second Where Prototype
public static IEnumerable<T> Where<T>(
this IEnumerable<T> source,
Func<T, int, bool> predicate);
The only difference it has from the first method is the predicate takes an additional argument which is the index of the element in the source collection.
Lets walk through some examples of where operator to see where we use the where operator.

In the above example, I am filtering the collection of integers to return only integers that are even numbers by passing the lambda expression which only evaluates to true when a certain number returns a remainder of 0. You can write the same query using query expression instead of writing it using the operator syntax. Here is how the example would look like.

The query syntax is much easier to read than the method syntax but then both yield the same result.
Lets modify the above query to use the second version of the where operator which has an additional argument of integer which is the index of the element in the source sequence. Since the second version of the where operator cannot be represented using the query syntax, we have to resort to the traditional method syntax to achieve the objective. Lets look at an example of that.

Looking at the above example you would notice that our lambda expression also makes use of the index of the element to only return elements which fall within the index of 0-3 and are even numbers.
Another interesting point that I discovered recently is where operator can appear more than once in a query. Lets look at an example of that.

From the above example, you would notice that I am applying the where clause twice, first to show numbers greater than 3 and then to retrieve numbers that are only evens.
Not only can you use where operator with linq to objects, but as mentioned earlier where operator can also be used in linq to SQL queries to apply filtering on the database side. I will drill through few examples to illustrate usage of where operator using northwind database.

In the above example to illustrate how the where operator gets converted to SQL, I am making use of the log property to log all the statements to the console window. You would notice that our where operator gets converted to where in SQL with equal to. But what if wanted a behavior of where Like instead of exact matching. Well, there are number of CLR methods that gets converted to like operator. The one that I found that gets interpreted as like are contains, StartsWtih, EndsWith and CompareTo. Lets look at an example to see the usage.


In the above example we are making use of contains, StartsWith and EndsWith method in .net which gets translated to SQL. Look at the SQL statement generated we can observer that contain operator have a list of two cities gets converted to in operator to select from a list of city. However StartsWith and EndsWith operator gets converted to Like operator with % passed in along with the value.
If the above method does not give you full control over the where clause generated by linq to sql, You can use SqlMethods.Like operator to exactly specify the like clause.
I wont be covering SqlMethods, since its a topic in itself that warrants a blog post. However I will demonstrate a small example that would show its usage in query syntax and the control it provides in generating the like statement that you desire.

From the above example, you would notice that we have full control over where we can put % sign to dictate in how much close proximity do we want our matches to be.
Distinct operator removes duplicate elements from input sequence.
The prototype for distinct operator looks like this
public static IEnumerable<T> Distinct<T>(
this IEnumerable<T> source);
Distinct operator basically enumerates over a sequence and returns objects that has not been previously returned. In order to determine if two items are same it uses gethashcode and equals method to identify if two values are the same.
Lets look at a simple example distinct operator to identify its usage.


Looking at the above example, you would notice that we have several numbers that are duplicates. By making use of the distinct operator we are only returning numbers that are not duplicate.
The same distinct concept can be applied to linq to sql. Lets look at an example of that.

In the above query, we are grab all the customerid for every order by traversing the customer property of the order. Since there will be many orders placed by a single customer, we apply a distinct operator to retrieve only unique customers.
Unfortunately there is no equivalent syntax of writing distinct in a query syntax and you have to resort to the method syntax to apply distinct operator.
One of the overload of distinct operator makes use of IEqualityComparer. What this allows you to do, is define your own implementation of wether two objects are equal or not. When you create your own IEqualityComparer, you basically have to implement two methods GetHashCode and Equals. Here is an example that makes use of IEqualityComparer to customize how two objects are considered equal.

Looking at our NameComparer class you would notice that the way we are defining how two names are equal, is by saying if the firstname for each name is same, then the names are considered equal. Then in our distinct operator we pass in that NameComparer which forces the query to return only two results because first names of both Zeeshan Jafar and Zeeshan Hirani happens to be the same.
Select Many Operator is part of the projection query operator supported by linq. SelectMany operator is mainly used for flattening out the hierarchy of collections into one single collection of objects. It merges each item into a single sequence that gets returned by the query results.
Here is the prototype for SelectMany operator
public static IEnumerable<S> SelectMany<T, S>(
this IEnumerable<T> source,
Func<T, IEnumerable<S>> selector);
The prototype takes IEnumerable of T and select delegate that returns IEnumerable of S. The selectmany operator will merge each zero or more output returned from the select delegate into one output sequence.
The second prototype for selectmany operator looks like this.
public static IEnumerable<S> SelectMany<T, S>(
this IEnumerable<T> source,
Func<T, int, IEnumerable<S>> selector);
The second prototype is not much different from the first prototype, except it passes the zero based index of the element to selector delegate.
Lets go through a simple example of how and where we can use selectmany operator.
We start off with an array of string which consists of complete name separated by space. In order to convert each name on its own, we make use of Selectmany operator passing the delegate an array of both names i.e the firstname and lastname by making use of split operator. As you can see from the result we have all the names broken apart into one big list.
This same query could also have been written using the query syntax as follows.

The result of the above query is exactly the same, except the query syntax is much easier to follow and more readable.
Not only can you use selectmany operator in linq to objects but selectmany operator can also be used with linq to sql to flatten a particular hierarchy. Lets look through an example of that.
In this case I am using linq to sql ormapper to generate my classes. In the first part of the query, i filter the customers who belong to the city of London and then using the selectmany operator i merge all the orders for all the customers into one big list of sequence.
This same method syntax can be written using query syntax as follows.
Interesting point to mention at this stage is, although I am applying the filter for the city earlier in my query, if I were to apply the filter later down in the query, it still would not have been a bottle neck for performance because the entire query gets converted to sql which gets sent to the database. However if you were to be using linq to objects then it would be an appropriate decision to apply the filter earlier down in the query.
I recently wrote an article on lambda expressions on codeproject.com
It talk in depth about how lambda expressions play in building linq query expressions.
http://www.codeproject.com/KB/cs/explore_lamda_exp.aspx
If you enjoy my article, pls comment so i can improve.
Thanks
Zeeshan Hirani
Delegates in C# has been around since 1.0. But every occasion when i want to use delegates i end up goggling for an example. so i decided to write a posting that i can consult every time for its basic usage.
Delegate allows a caller and target to compromise on a definition of a method which includes the parameter type and its return type. Delegates provide a level of indirection because it allows you to dynamically wire a method to the target using callback mechanism.
Lets drill through the above example to identity key behaviors to remember. I am first declaring a delegate that returns a boolean and accepts an integer. We then specify two different implementations of that delegate. Both those implementations needs to meet the method definition specified by the delegate. Notice that IsEven is declared as static method and IsGreaterThan5 is declared as instance level method and both of them complies to the definition of the delegate.
In static void main we create an instance of Program class and call Run method on it. As we proceed further in exploring the code i will explain why i went through the trouble of creating an instance of the class and calling run method on it. For now let's move on further with our exploration of the code.
In the run method, we create a reference to the delegate Check and assign it to a method. Notice we are using short hand version of assigning a method to a delegate. We could equally written this line of code as follows
Check iseven = new Check(IsEven);
This was the syntax that was around 1.1. With C# 2.0 you can now use a simpler syntax to a assign a method.
In the next line we assign a second method to the delegate. This is called the multicast delegate where a delegate method references more than 1 target or method. The plus += operator is used to add those methods to the invocation list. We then call the delegate as if we are calling a method but in this case it actually calls both implementations of the delegates IsEven and IsGreaterThan5. One drawback to the way we are calling the delegate is, if your delegate's method definition has return type other than void and you are using multicast delegates than you will only receive the value returned from the last method added to the invocation list. Value returned from the methods added to invocation list prior to the last one would be lost.
In the last section of the code we are actually calling the target to check to see if it evaluates to the instance we are in and result is true. This illustrates a very important concept that when a delegate points to a method that is an instance level as compared to static, then it is the responsibility of the delegate to maintain both the reference to the method as well as a reference to the instance of that method.
Another concept that i consider discussing in terms of delegate is covariance. Its a feature in the delegate which allows polymorphic behavior. Basically if your delegate return type is an Person, you do not necessarily have to return Person type from the implementations of that delegate. Your implementation could actually return concrete type of Person such as an Employee
From the example above you will observe that our delegate returns a Person but our implementation of the method actually returns an employee. When we invoke the delegate, since the return type of the delegate is Person we need to cast it to employee to get the more specific class.
Although javascript is truly not an object oriented languange, microsoft with the release of client side framework for ajax, had really made working with javascript much easier. Today i will explore the concepts for javascript intellisense, notifying asp.ne ajax framework of any external client side libraries and how to create classes and use inheritance to extend those classes.
To start off i will create a simple class called person in the javascript file called Person.js. Person class will contain a property called Name and a methods called Print.
At the top of the file you will notice a comment which includes MicrosoftAjax.js. This directive is used by visual studio 2008 to provide you intellisense for the microsoft ajax library. Intellisense can simply be provided by adding the comment directive at top of your JavaScript file. Notice that we using the name attribute to reference a JavaScript file that is embedded in an assembly called System.Web.Extensions.dll.
We create a person class by first initializing the name private variable in the constructor which is typically a function. The naming convention is irrelevant in terms of javascript because javascript has no notion of private variable. However by attributing private variables with underscore, intellisence recognizes it as private variable and ensures that its not visible outside the scope of the class.
Next down we go ahead and create getter and setter for the name property and create a method called Print which simply prints the name variable using alert box.
After creating the class we go ahead and register the class with the asp.net ajax client side libraray by passing the name of the class in the registerClass method. registerClass happens to be a method defined on the Type object.
We then finally notify the ajax client side framework that we have finished loading this javascript file. It is recommended practice to call notifyScriptLoaded on every javascript file to notify asp.net ajax.
We will move forward by creating another class by extending Person class with class Student. Student will have one extra property called SSN and will override the Print method. Lets drill through the Student javascript class.
We wont be covering all the details about the class except for few noticeable items worth mentioning. First notice the comment directive for intellisence uses path variable instead of name and that is because the javascript file we are trying to reference is not embedded in the assembly and belongs to our project. We are also making use of a concept introduced by asp.net ajax client side library called namespace registration. Concept of namespaces only exists in C# and vb.net or other programming langauges. Namespaces helps in preventing naming conflicts by keeping related classes together. The concept was great enough for Microsoft to introduce the registernamespace method in the client side library. It allows you add a particular class to the namespace registered above.
After registering we go ahead and add a property called ssn and override the print method defined in the person class. In order to access a property defined in the base class, we make use of callBasemethod passing in the name of the method whose value we like to get and then concatenating the results with ssn variable declared inside the Student class. We then go ahead and regsiter the class with ajax client side library but this time we use the second overload which lets u specify the class you are inheriting from which happens to be People.Person class.
Now that we have those two classes ready we can go ahead and create instances of Student class and call Print method to display the result. Here is how the code looks like.

There is not much to talk about in this code except that we are registering the two JavaScript files with scriptmanager and then inside the pageload function we create an an instance of Student class. We then assign the values to Name and ssn and call print to get an alert dialog on the screen that looks like the screen shot below
In this blog posting, i walked you through how to create simple class in javascript that extends other class. We also discussed how namespaces can be used to resolve naming conflicts. I hope this walk through was informative.
I recently wrote another article on codeproject which talks about linq to sql execution plan. Pretty long but worth the read. Hope you guys will enjoy!
http://www.codeproject.com/KB/linq/LINQ_to_SQL.aspx
I wrote an article not to long ago on CodeProject.com which talks about linq query operators and differed execution plans.
Here is the link.
http://www.codeproject.com/KB/linq/linq_in_dept.aspx
OK its pay back time. Over the last 3 years working as a .NET developer I had made significant progress in my life. It all due to extraordinary developers contributing to our community and teaching us good practices to write and produce better software. I have acknowledged the fact that more you teach other people, the better you get. My journey begins here. There is no better way to serve the community than to participate in writing blogs and converse about new thing that I discover while performing my daily jobs at work. I will strive to write good content to help other fellow developers with my knowledge contribution. This blog will serve as a vessel for my technical thoughts as well as my personal ones.
Obviously there are certain trade offs I would have to make in order for me to dedicate more time to writing blog entries. However I see embarking on this opportunity as a way to improvise my communication skills and be more lucid in expressing my thoughts. Asp.net has not only been my profession but a drive that motivates me to develop myself everyday as a software developer. I will endeavor to make good impact on the software community with my share of knowledge in .net. So wish me best of luck in making the most intricate change in my life!
More Posts