How to Change the Return Type in Linq : Select operator

When I was started with Linq, I stuck many times on what the query will return, how to change return type of query? Sometimes our linq code need specific result as requirements.

Introduction

We often write SQL query for database systems when it need to fetch stored data and we explicitly specify a set of columns to return, like:

The main goal for limiting the number of column is:

  1. Return only those necessary for query in order to improve performance.
  2. And, limit network traffic

The first statement return every column and row of the Employee table; whereas second will return only the three columns explicitly for all row, it save server and network resources.

Similarly select operator in LINQ query expressions provide the same task, and it provides powerful control over how and what data shape is returned from a query expression.

There are different ways a select clause can return results:

  1. As a single result value or element
  2. In an IEnumerable<T> where T is of the same type as the source items
  3. In an IEnumerable<T> where T is any existing type constructed in the select projection
  4. In an IEnumerable<T> where T is an anonymous type created in the select projection
  5. In an IEnumberable<IGrouping>, which is a collection of grouped objects that share a common key

Return a single result value or element

Some of the Linq query operators return a single value as the result, or a single element from the source collection.

Set of Operators that Return a Specific Result Value Type

  1. Numeric result Type : Aggregate, Average, Max, Min, Sum, Count, LongCount
  2. Boolean result type : Any, All, Contains, SequenceEqual
  3. Type <T> result type : ElementAt, ElementAtOrDefault, First, FirstOrDefault, Last, LastOrDefault, Single, SingleOrDefault, DefaultIfEmpty

For example

Above example, first query returns “true” and second the last element from employee collection.

IEnumerable<T> : return of the same type as the source collection

The basic features of select operator is to returns a filtered and ordered subset of the original source items. This projection is achieved by specifying the range variable as the argument after the select keyword. The following example returns an IEnumerable, with the type Contact being inferred from the element type of the source collection.

Both query in example return a list of type Employee implicitly because employees is Employee collection.

Using Linq extension method we can complete same task like below example:

IEnumerable<TAny> : Return a Different Type

We can return any type from select clause, not only source type (i.e. collection type). The target type can be any type that manually constructed with a new statement. When creating return type we can follow these two approach:

  1. Create parameterized constructor containing all of the parameters, that we specifically need which we simply call that constructor, or
  2. We can use type initializer

Personally I prefer to use of type initializer syntax, because it frees us from having to define a specific constructor each time a new projection signature is needed.

Lets see how to select return a type, using both approach :

Suppose we have to select Person List from employee, first create a Person class.

Now we have to select person list from Employee collection:

IEnumerable<TAnonymous> : Return an Anonymous Type

Anonymous types is created by compiler on-the-fly based on the object initialization exression, to know more about anonymous type click here.

The following query shows returning to an IEnumerable>T< collection where T is an anonymous type:

The anonymous type created in the above example is composed of two properties, Name and Address.

IEnumerable<IGrouping<TKey,TElement>> : Return a Set of Grouped Objects

Grouping in LINQ enables to return partitioned sets of data from a collection based on a given key value.
Following example simple group by query:

Conclusion

This article describe the basic query of filtering, ordering, and selecting the results into any resulting form we need.

Leave comment or any suggestion or regarding this article

Happy Reading šŸ™‚

Advertisements

3 thoughts on “How to Change the Return Type in Linq : Select operator

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s