1

I have a table called Events and these are example of EndDate columns:

enter image description here

I am trying to extract months from these events, but I want them to be like: 11, 12, 1 (11 and 12 from current year, and 1 is from next year - 2013).

var ev = db.Events.Select(d => new { Month = d.StartDate.Value.Month, 
                                     EndDate = d.EndDate })
                  .Where(d => (d.EndDate >= DateTime.Now
                           || (   d.EndDate.Value.Day == DateTime.Now.Day 
                               && d.EndDate.Value.Month >= DateTime.Now.Month) ))
                  .OrderBy(d => d.EndDate.Value.Year)
                  .Select(d => new { Month = d.Month }).Distinct();

Well, I don't understand why this query does not work. It extracts months as: 1, 11, 12 which of course, is not what I want...

Ps: You can ignore where clause, that is only filtering the events from now on.

4

4 回答 4

3

您仅按年份排序,.OrderBy(d => d.EndDate.Value.Year)但您可能希望按d.EndDate.Value

仅年份将忽略日期的任何天/月部分......因此列表中的“第一个”2012 是第一项。

    var events = new List<DateTime>
    {
        new DateTime(2013,11,1),
        new DateTime(2013,5,1),
        new DateTime(2013,4,1),
        new DateTime(2012,12,29),
        new DateTime(2012,12,28)
    };

    var ev = events.Select(d => new { Month = d.Month, Date = d })
        .Where(d => (d.Date >= DateTime.Now || (d.Date.Day == DateTime.Now.Day && d.Date.Month >= DateTime.Now.Month)))
        .OrderBy(d => d.Date.Year)
        .Select(d => new { Month = d.Month })
        .Distinct();

将返回12,11,5,4

var ev = events.Select(d => new { Month = d.Month, Date = d })
                .Where(d => (d.Date >= DateTime.Now || (d.Date.Day == DateTime.Now.Day && d.Date.Month >= DateTime.Now.Month)))
                .OrderBy(d => d.Date)
                .Select(d => new { Month = d.Month })
                .Distinct();

将返回12,4,5,11

于 2012-11-20T09:10:39.613 回答
1

这可能不是它,但我在文档中看不到任何Enumerable.Distinct()保证结果的任何给定顺序。您可能想重新调整您的查询以检查是否是这种情况。

于 2012-11-20T09:05:38.037 回答
1

将 Order 语句更改为:

.OrderBy(d => d.EndDate.Value.Year).ThenBy(d => d.EndDate.Value.Month)

于 2012-11-20T09:12:05.257 回答
0

如果您有日期枚举并且只想获取月份数字,则可以按顺序执行以下操作:

var months = dates
    .Select(d => new { Month = d.Month, Year = d.Year })
    .Distinct()
    .OrderBy(a => 12 * d.Year + d.Month)
    // or .OrderBy(a => a.Year).ThenBy(a => a.Month)
    .Select(a => a.Month);

请注意在您摆脱年份之前Distinct的电话意味着例如将返回,我认为这是您想要的。1/1/2011, 5/5/2011, 1/1/20121, 5, 1

您可以将此查询附加到过滤日期列表中;不过,您需要给它一个日期列表,而不是您目前正在构建的任何匿名对象的列表。

于 2012-11-20T09:12:46.747 回答