Reputation:
Let's say I have a employee list
var employeeGroup = from emp in Employee.GetAllEmployees()
group emp by emp.Department;
//why no need to use "select" here
I don't know why there is no need to add a "Select" in the end of the linq. If I want to retrieve the employee instances, then it should be :
var employeeGroup = from emp in Employee.GetAllEmployees()
select emp;
Upvotes: 1
Views: 83
Reputation: 12
Both the linq yields different results. The first linq groups the results based on department and the second one fetches all the records directly. For example, Say there are 5 records in table Record1 - dep1 Record2 - dep2 Record3 - dep3 Record4 - dep2 Record5 - dep1
The first linq result would be dep1 dep2 dep3 The group will appear as a single record
The second linq result would be dep1 dep2 dep3 dep2 dep1
Basically the query should end with a select or group clause. Hope it helps.
Upvotes: 0
Reputation: 23732
The documentation tells:
The group clause returns a sequence of IGrouping
<TKey, TElement>
objects that contain zero or more items that match the key value for the group.
EDIT:
Taking a look at the Query Expression Basics into the section:
it states that:
A query expression must end with either a select clause or a group clause.
A look into the Select clause documentation reveals that:
In a query expression, the select clause specifies the type of values that will be produced when the query is executed. [...] A query expression must terminate with either a select clause or a group clause. [...]
Use the group clause to produce a sequence of groups [...]
Use the select clause to produce all other types of sequences [...]
It seems that the specification of the return type is the decisive point. Since the group by clause specifies the return type it is not necessary anymore to make an extra select, in contrast to where (as mentioned by Tim Schmelter).
Upvotes: 2