Linq选择行当月的日期 [英] Linq Select row Where date in Current month

查看:104
本文介绍了Linq选择行当月的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取当月的数据.无法找到有效的解决方案.

I need to get data from the current month.Haven't been able to find a solution that works.

这是我的代码,可以为我提供所需的数据,但我是从整个月(而不是从当前月份)获得数据.

This is my code, which gives me the data I need, but I get data from a whole month back, instead of from the current month we are in.

我用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的答案奏效了,尽管不是最底下的答案.

Keyur patel' answer worked, though not for the bottom one.

所以我要为此感谢Jules:

so there i have to thank Jules for this one:

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

推荐答案

尝试使用此功能:

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的支票,因为它可能与其他年份的月份匹配(如果有).

Added check for .Year since it may match with months from other years, if you have any.

修改

至于假期部分:

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(),
});

这篇关于Linq选择行当月的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆