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.
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:
- Return only those necessary for query in order to improve performance.
- 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:
- As a single result value or element
- In an IEnumerable<T> where T is of the same type as the source items
- In an IEnumerable<T> where T is any existing type constructed in the select projection
- In an IEnumerable<T> where T is an anonymous type created in the select projection
- 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
- Numeric result Type : Aggregate, Average, Max, Min, Sum, Count, LongCount
- Boolean result type : Any, All, Contains, SequenceEqual
- Type <T> result type : ElementAt, ElementAtOrDefault, First, FirstOrDefault, Last, LastOrDefault, Single, SingleOrDefault, DefaultIfEmpty
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:
- Create parameterized constructor containing all of the parameters, that we specifically need which we simply call that constructor, or
- 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:
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 🙂