Select current week using LINQ - c#

How do I write the where statement that select records with Date field between Sunday to Saturday of a given date.
Data Fields: Id, Name, Date

Where date is the date in question, how about:
DateTime start = date.Date.AddDays(-(int)date.DayOfWeek), // prev sunday 00:00
end = start.AddDays(7); // next sunday 00:00
var qry = from record in data
where record.Date >= start // include start
&& record.Date < end // exclude end
select record;

DateTime givenDate = DateTime.Today;
DateTime startOfWeek = givenDate.AddDays(-1 * givenDate.DayOfWeek);
DateTime endOfWeek = startOfWeek.AddDays(7);
var query = myObjects
.Where(ob => startOfWeek <= ob.DateField && ob.DateField < endOfWeek)

Related

How do I use an IF statement on a datetime from Dictionary<string, List<datetime>> in C#

The data I am pulling from the database is (string, datetime) and I need to review datetime to see if it equals sysdate today # 14:00, but i can't figure out how to just look at the datetime field from list.
int recordCount;
using (IDatabase db = SystemStatus.GetDatabase(_connectionStrings.stuff))
{
const string query= #"
SELECT DISTINCT string, date
FROM table
WHERE date > DATE_SUB(SYSDATE(), Interval 30 day) AND
drop_date < DATE_SUB(NOW(), Interval 12 hour) AND
status_id = 2;";
var records = db.Fetch<Dictionary<string, List<DateTime>>>(query);
recordCount = records.Count;
}
You need a datetime object for your comparison:
DateTime now = DateTime.Now;
DateTime dt = new DateTime(now.Year, now.Month, now.Day, 14, 0, 0); // 2 PM today
You don't need an "if" statement. You need to use object querying (LINQ)...
using System.Linq;
// get everything past 2 PM today
var after2PMRecords = records.Where(r => r.Value > dt);
// get everything before 2 PM today
var before2PMRecords = records.Where(r => r.Value < dt);

How to generate previous months orders from db using linq or lambda?

I have tried this:
var date = DateTime.Now.AddMonths(-1);
var lastMonth = ( from lm in db.Orders
where lm.Saved> date
select lm).ToList();
This generates this month and previous month. I only need last month, how can I solve this using linq or lambda?
You need to generate the minimum and maximum dates and query records between those 2 dates.
var today = DateTime.Today;
var max = new Date(today.Year, today.Month, 1); // first of this month
var min = max.AddMonths(-1); // first of last month
var lastMonth = ( from lm in db.Orders
where lm.Saved >= min && lm.Saved < max
select lm).ToList();

Get data based on two dates values filtered by month

I have list of events, each event has two dates; start date and end date. I want to create a filter by months. How do I return dates that ranges between a month that a user selects?
for example, lets say the user selects month October, I want to return all events that are within this month.
I have used this to get the dates that ranges between todays date but now stuck on how to get the range between a month.
DateTime dateToCheck = DateTime.Today.Date;
DateTime startDate = DateTime.Parse(item["Start Time"].ToString());
DateTime endDate = DateTime.Parse(item["End Time"].ToString());
foreach (SPListItem item in collection)
{
if (startDate <= dateToCheck && dateToCheck < endDate)
{
ListBox1.Items.Add(item["EventTitle"].ToString());
}
}
// set up dummy data
var dates = new[] {DateTime.Now, DateTime.Now, DateTime.Now};
int month = GetMonth();
// get result
var result = dates.Where(date => date.Month == month);
EDIT: if you need to make sure the dates have the correct year as well, use
var dates = new[] {DateTime.Now, DateTime.Now, DateTime.Now};
int year = GetYear();
int month = GetMonth();
var result = dates.Where(date => date.Year == year && date.Month == month);
Of course, you can get the year/month numbers as well as the date-list from wherever.
EDIT2: if you get a DateTime object as input modify accordingly:
var dates = new[] {DateTime.Now, DateTime.Now, DateTime.Now};
var input = GetDateTime();
var result = dates.Where(date => date.Year == input.Year && date.Month == input.Month);
You still can use your code with little modifications. As start date you have to select 00:00 time of 1st of the month and as end date you have to use 00:00 time of 1st of the next month. In case of October 2015 it would be: 1 Oct 2015 <= date < 1 Nov 2015.
int year = 2015;
int month = 10;
DateTime dateToCheck = DateTime.Today.Date;
DateTime startDate = new DateTime(year, month, 1);
DateTime endDate = startDate.AddMonths(1);
foreach (SPListItem item in collection)
{
if (startDate <= dateToCheck && dateToCheck < endDate)
{
ListBox1.Items.Add(item["EventTitle"].ToString());
}
}

Creating a LINQ query that will include all entries from the current week excluding today and yestreday

I am working on a LINQ query to retrieve all records from the current week, however, I need to exclude any records from today and yesterday.
Here is what I have so far:
DateTime startThisWeek = DateFunctions.GetFirstDayOfWeek(DateTime.Now).AddDays(1);
DateTime endOfThisWeek = startThisWeek.AddDays(6);
DateTime today = DateTime.Now;
DateTime yesterday = DateTime.Now.AddDays(-1);
var notificationList =
(from n in db.DashboardNotifications
.OrderByDescending(n => n.NotificationDateTime)
where (n.NotificationDateTime >= startThisWeek &&
n.NotificationDateTime <= endOfThisWeek) &&
(n.NotificationDateTime != today &&
n.NotificationDateTime != yesterday)
select n).ToList();
The problem with above query is that it is not returning proper records , it also showing todays records too.
Assume your DateFunctions.GetFirstDayOfWeek works correctly
DateTime startThisWeek = DateFunctions.GetFirstDayOfWeek(DateTime.Now);
DateTime yesterday = DateTime.Today.AddDays(-1);
var notificationList =
(from n in db.DashboardNotifications
where n.NotificationDateTime.Date >= startThisWeek.Date &&
n.NotificationDateTime.Date < yesterday)
orderby n.NotificationDateTime descending
select n).ToList();
Comments: If start of current week is not before yesterday, then you will simply get no records. Otherwise yesterday always will be before current week end.
How to get start of week correctly:
public static class DateTimeExtensions
{
public static DateTime StartOfWeek(this DateTime date,
DayOfWeek startOfWeek = DayOfWeek.Monday)
{
DateTime result = date;
while (result.DayOfWeek != startOfWeek)
result = date.AddDays(-1);
return result.Date;
}
}
You are only excluding records for today and yesterday if they have the same time as when you run the report.
Try
DateTime startThisWeek = DateFunctions.GetFirstDayOfWeek(DateTime.Now.Date).AddDays(1);
DateTime endOfThisWeek = startThisWeek.AddDays(6);
DateTime today = DateTime.Now.Date;
DateTime yesterday = DateTime.Now.Date.AddDays(-1);
var notificationList =
(from n in db.DashboardNotifications
.OrderByDescending(n => n.NotificationDateTime)
where (n.NotificationDateTime >= startThisWeek &&
n.NotificationDateTime.Date <= endOfThisWeek) &&
(n.NotificationDateTime.Date != today &&
n.NotificationDateTime.Date != yesterday)
select n).ToList();
This is assuming that it is possible to have future notifications.
Ps, I'm not sure what the DateFunctions.GetFirstDayOfWeek method does nor why you are adding 1 day to it.

Convert only date to Date and Time format in c#

I want to count data of each day from database using the for loop. Here, I don't know to get the begining of day (start from 12 am) and end of that day ( 12 pm) from value of only date. In below code startDate and endDate have only date value e.g. 2/11/2012.
for (DateTime dates = startDate; dates <= endDate; dates.AddDays(1))
{
DateTime BeginingOfDay = begining of value variable dates; // 2/2/2012 00:00:00
DateTime EndOfDay = at end of value variable dates; // 2/2/2012 23:59:59
int count = (from u in db.CDRs where (u.StartTime >= BeginingOfDay && u.StartTime <= EndOfDay) select u).Count();;
dictionary.Add(dates.ToString("MM/dd/yyyy"), count);
}
The best way to deal with this is to use the right combination of lessthan/greaterthan operators with midnight on day n, and midnight on day n+1
so given a day, eg
var date = new Date(2012,8,24); // today
get midnight on that day (start of the day)
var start = new Date(date.Year, date.Month, date.Day, 0,0,0); // could also be date.Date
and to get midnight on the next day just add 1 day
var end = start.AddDays(1);
now use greater-than-or-equal-to for the start, and less-than for the end:
var inRange = x.StartTime>=start && x.EndTime<end
Put together into your example becomes:
for (DateTime dates = startDate; dates <= endDate; dates.AddDays(1))
{
DateTime BeginingOfDay = new DateTime(dates.Year,dates.Month,dates.Day,0,0,0);
DateTime EndOfDay = BeginingOfDay.AddDays(1);
int count = (from u in db.CDRs where (u.StartTime >= BeginingOfDay && u.StartTime < EndOfDay) select u).Count();;
dictionary.Add(dates.ToString("MM/dd/yyyy"), count);
}
This should get you the results you want:
using(var dataContext = new YourDataContext())
{
var dictionary = dataContext.CDRs.GroupBy(u => new
{
u.StartTime.Year,
u.StartTime.Month,
u.StartTime.Day
})
.Select(g => new{ Date = g.Key, Count = g.Count() })
.ToDictionary(g => new DateTime(g.Key.Year, g.Key.Month, g.Key.Day), g=>g.Count);
return dictionary;
}

Categories