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