Orderby statement uses First() method call, why is it needed?

157 Views Asked by At

I'm new to Linq and I'm wondering why the First() method call is needed when ordering by the County in the following query. Also, after knowing why it is needed, could the same result be accomplished by using the Last() method?

var hsQ = from hspt in hospitals
          orderby hspt.City
          group hspt by hspt.County into hsptGroup
          orderby hsptGroup.First().County
          select hsptGroup;

Note: The above example is part of a Question/Answer from a book I'm reading, and the type hospitals is not defined explicitly for me to see.

2

There are 2 best solutions below

6
On BEST ANSWER

That is because hsptGroup holds a group of hospitals, not a single hospital.

Even though all the hospitals in this group have the same county, you still need to specify .First(), so you can reference a single hospital's county.

0
On

Actually that First is used to access First Element in the Collection of items Grouped. So subsequently the ordering is done on the basis of the First Item's County. Yes you can do Last and that way ordering will be done on the basis of last item in the Grouped Collection.