Linq Select row Where date in Current month
16,748
Solution 1
Try using this:
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
};
Added check for .Year
since it may match with months from other years, if you have any.
Edit
As for the holiday part:
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(),
});
Solution 2
You can simply compare only Month part of the date like this:
timeEntry.DateEntity.Month == DateTime.Now.Month
Solution 3
You can use Month
and Year
properties of the DateTime class as follows:
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
}
);
Author by
andrelange91
I am a web developer in denmark, odense. What more is there to say ?
Updated on June 14, 2022Comments
-
andrelange91 almost 2 years
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.
I chose the date "limit" twice with
row > DateTime.Today.Addmonths(-1)
Any ideas ?
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(), });
EDIT:
Keyur patel' answer worked, though not for the bottom one.
so there i have to thank Jules for this one:
DateTime.Today.AddDays((DateTime.Today.Day -1) * -1)