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.


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

Continue reading


Linq’s Where Clause (operator) : Result Filtering

One of the main task of a Linq query is to filter the results from a larger collection on some criteria. This is perform by Where operator, which tests each element within a source collection and returns only those elements that pass when tested against a given predicate expression.


A predicate is simply an expression that takes an element of the items in source collection and returns true or false.

The extension method for the Where operator is very simple; it iterates the source collection using a foreach loop, testing each element and return passed elements. Here is the actual code in the System.Linq library:

Continue reading

LINQ to Objects C# : Introduction

In this post, I discuss about LINQ to object, an amazing features of C# which is introduced in C# 3.0.


Linq is libraries built by Microsoft to make working with data (for example, a collection of in-memory objects, rows from a database table, or elements in an XML file) simpler and more natural.

LINQ has changed the approach to writing data driven applications. Code is become simpler, often faster, and easier to read.

For demonstrate the approach to coding problem with and without using LINQ, I’ll show example that find out vision how coding practice without LINQ changed with using LINQ.

Example is that there is employee list which is to be sorted accoring to their name and grouped sort by their Department name.
Continue reading