Linq选择行当前月份中的日期

时间:2016-09-21 07:14:19

标签: c# linq datetime

我需要从当月获取数据。但是找不到有效的解决方案。

这是我的代码,它为我提供了我需要的数据,但是我从一个月前收到数据,而不是从我们当前所在月份开始。

我使用row > DateTime.Today.Addmonths(-1)

选择了日期“限制”两次

有什么想法吗?

var userQuery = 
from timeEntry in TimeEntries
                                //this displays a month back, not current month TODO: change to current month.
where timeEntry.DateEntity > DateTime.Today.AddMonths(-1)
select new {
    UserName = timeEntry.User.FirstName + " " +timeEntry.User.LastName,
    HoursEntered = timeEntry.HoursEntered,       
    User = timeEntry.User
};

var localrows = userQuery.ToList();

var grouping = localrows.GroupBy(x => x.User);

var userList = grouping.Select(q => new {
    UserName = q.FirstOrDefault().UserName,
    Hours = q.Sum(hr => hr.HoursEntered),                 //AbsenceTypeID = holiday(1)                          // still takes from a whole month, instead of current month.
    Holiday = q.FirstOrDefault().User.Absences.Where(a => a.AbsenceTypeID == 1).Where(date => date.DateEntity > DateTime.Today.AddMonths(-1)).Count(),
});

编辑:

Keyur patel的答案有效,但不是最底层的。

所以我要感谢Jules这个:

DateTime.Today.AddDays((DateTime.Today.Day -1) * -1)

3 个答案:

答案 0 :(得分:6)

尝试使用:

DateTime today = DateTime.Today;
var userQuery = 
from timeEntry in TimeEntries
where timeEntry.DateEntity.Month == today.Month && timeEntry.DateEntity.Year == today.Year
select new {
    UserName = timeEntry.User.FirstName + " " +timeEntry.User.LastName,
    HoursEntered = timeEntry.HoursEntered,       
    User = timeEntry.User
};

添加了对.Year的检查,因为它可能与其他年份的月份相匹配(如果您有)。

修改

假期部分:

var userList = grouping.Select(q => new {
    UserName = q.FirstOrDefault().UserName,
    Hours = q.Sum(hr => hr.HoursEntered),
    Holiday = q.FirstOrDefault().User.Absences.Where(a => a.AbsenceTypeID == 1 && a.DateEntity.Month == today.Month && a.DateEntity.Year == today.Year).Count(),
});

答案 1 :(得分:1)

您可以使用DateTime类的MonthYear属性,如下所示:

var userQuery = TimeEntries
  .Where (te => te.DateEntity.Month == DateTime.Today.Month && te.DateEntity.Year == DateTime.Today.Year)
  .Select(timeEntry => 
    new {
      UserName = timeEntry.User.FirstName + " " + timeEntry.User.LastName,
      HoursEntered = timeEntry.HoursEntered,       
      User = timeEntry.User
    }
  );

答案 2 :(得分:1)

您只需比较日期的月份部分,如下所示:

timeEntry.DateEntity.Month == DateTime.Now.Month