Code Example
In this example, we are going to fetch the top name of the person who works with the project "TAAGUNG". The table structure and data are as below.

Table Structure and Data
For this, we will be using the same query with different return types as shown below. Certainly, they return the same result.
- static void QueryWithIEnumerable(StudyEntities studyEntities)
- {
- IEnumerable<PROJECT_TEAM> projects =
- studyEntities.PROJECT_TEAM.Where(e => e.PRJ_ID.Equals("TAAGUNG"));
- Console.WriteLine(projects.ToString());
- projects = projects.Take(1);
- Console.WriteLine(projects.ToString());
- foreach (var project in projects)
- {
- Console.WriteLine(project.FRST_NM + " " + project.LAST_NM);
- }
- }
- static void QueryWithIQueryable(StudyEntities studyEntities)
- {
- IQueryable<PROJECT_TEAM> projects =
- studyEntities.PROJECT_TEAM.Where(e => e.PRJ_ID.Equals("TAAGUNG"));
- projects = projects.Take(1);
- Console.WriteLine(projects.ToString());
- foreach (var project in projects)
- {
- Console.WriteLine(project.FRST_NM + " " + project.LAST_NM);
- }
- }
How does it work?
For IQueryable, the generated query is this. Please note the TOP(1) in the first line.
- SELECT TOP (1)
- [Extent1].[PRJ_ID] AS [PRJ_ID],
- [Extent1].[FRST_NM] AS [FRST_NM],
- [Extent1].[LAST_NM] AS [LAST_NM]
- FROM (SELECT
- [PROJECT_TEAM].[PRJ_ID] AS [PRJ_ID],
- [PROJECT_TEAM].[FRST_NM] AS [FRST_NM],
- [PROJECT_TEAM].[LAST_NM] AS [LAST_NM]
- FROM [dbo].[PROJECT_TEAM] AS [PROJECT_TEAM]) AS [Extent1]
- WHERE 'TAAGUNG' = [Extent1].[PRJ_ID]
While IEnumerable generates the following SQL query and then performs in-memory filtering of data, i.e., getting the required data is a two-step process.
- SELECT
- [Extent1].[PRJ_ID] AS [PRJ_ID],
- [Extent1].[FRST_NM] AS [FRST_NM],
- [Extent1].[LAST_NM] AS [LAST_NM]
- FROM (SELECT
- [PROJECT_TEAM].[PRJ_ID] AS [PRJ_ID],
- [PROJECT_TEAM].[FRST_NM] AS [FRST_NM],
- [PROJECT_TEAM].[LAST_NM] AS [LAST_NM]
- FROM [dbo].[PROJECT_TEAM] AS [PROJECT_TEAM]) AS [Extent1]
- WHERE 'TAAGUNG' = [Extent1].[PRJ_ID]
Based on this, we can easily depict the processing of these two in the following 2 images.
Moreover, we can see above that the query is written in two statements. If our LINQ is written in one statement like this,

Mohanraj KaliappanPosted Feb 14, 2019, 6:07 AM
Very Nice Article