简体   繁体   English

LINQ orderby和组

[英]LINQ orderby and group

Consider the following code 考虑以下代码

var res = from d in CalEntries
    group d by d.date.ToString("MMMM") into grp
    orderby grp.Key 
    select grp;

I have a list of objects in CalEntries where one member property is date of type DateTime . 我有一个对象在CalEntries一个列表,其中一个成员属性是date类型的DateTime Currently this code returns me all the dates grouped by the month name however the order of the groups is alphabetic so November would appear before October for example. 目前,此代码返回给我按月份名称分组的所有日期,但是分组的顺序是字母顺序的,因此例如11月将出现在10月之前。 How can I modify this query to retain the grouping on the month name but to order the groups based on the months chronological order? 如何修改此查询以保留月份名称上的分组,但根据月份的时间顺序对分组进行排序?

It is really backwards to group by the name of the month if you don't care about the month name at all. 如果您根本不关心月份名称,那么按月份名称分组确实是倒退。 Instead, group directly by the month number and sort by it. 而是直接按月份编号分组并按其排序。 Don't compute with strings if the native format of your data is more suitable. 如果您的数据的本机格式更适合,请不要使用字符串进行计算。

group x by x.Month into g
orderby g.Key
select new { MonthName = g.Key.ToString("MMMM"), Items = g.ToList() }

您可以尝试:

orderby d.date.ToString("MM") ascending

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM