开发者

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

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 exam开发者_运维问答ple is part of a Question/Answer from a book I'm reading, and the type hospitals is not defined explicitly for me to see.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜