Get Next Meeting Date fails using Linq query - c#

I need to display the next Meeting Date from a table of meeting dates. Once a date passes as current, the next date is supposed to show up. I've searched for similar examples but no luck:
05/21/2019
07/11/2019
08/08/2019
09/12/2019
10/10/2019
11/14/2019
12/12/2019
Here the Linq query I have that fails. It doesn't return anything for example after the 10/10/2019 date because 11/14/2019 is actually more than 1 month.
var LinqResult = (from c in _context.MeetingSchedule
where c.MeetingDate.Date >= DateTime.Now.Date && c.MeetingDate.Date <= DateTime.Now.Date.AddMonths(1)
select new { c.Location, c.MeetingDate, c.MeetingTime }).ToArray();
if (LinqResult.Any())
{
//SEND NEXT MEETING DATE BACK VIA VIEWSTATE
}
Also, I am pretty sure something odd is going to happen on the last month of the year after the meeting happens (December).
I am trying to show the current next meeting, and have it change to the next meeting after that once the current one is over. Adding a month to 12 will create a month number 13 which is non-existent.

You can sort meeting schedule ascending after filtering out dates that have already happened then just grab the first one.
var LinqResult = (from c in _context.MeetingSchedule
where c.MeetingDate.Date >= DateTime.Now.Date
orderby c.MeetingDate.Date
select new { c.Location, c.MeetingDate, c.MeetingTime }).ToArray();
if (LinqResult.Any())
{
//SEND NEXT MEETING DATE BACK VIA VIEWSTATE
}

Related

Determining Date Overlapping in a list of dates

I have a list of items that each have a start and end date time component.
var myDates= new List<Tuple<DateTime, DateTime>>();
Which I fill it out with some date.
Now I wanted to loop through them and see if any two of those have any overlapping date rang. So I did this:
var myOverlapList = (from start in myDates
from endDate in myDates
where !Equals(start, end)
where start.Item1 <= end.Item2 && start.Item2 >= end.Item1
select end);
It works when dates have overlap for example one day back and forth between two dates BUT it does NOT work when two date entries have the EXACT SAME values.
So how I can fix my code or just something else to achieve that.
The
where !Equals(startDate, endDate)
line, which is supposed to filter out the same date tuple actually is filtering out any duplicate, so any matching timespan falls out of the selection. So your query will return all DateTime tuples, which overlap with some other tuple in the collection, but only unique. And you want also to return tuples if they encounter in your collection more then once.Your problem, actually is that you can not differentiate between two different items with the same value. So you need a discriminator for them and because you use a list, the index of an item fits well. You can cast your Tuple<DateTime, DateTime> collection into, e. g. {int id, Tuple<DateTime, DateTime> range} object by
var datesWithId = dates.Select((d, i) => new {id = i, range = d});
and then modify your query like this:
var anyOverlap = (from startDate in datesWithId
from endDate in datesWithId
where startDate.id!=endDate.id
&& startDate.range.Item1 <= endDate.range.Item2
&& startDate.range.Item2 >= endDate.range.Item1
select endDate.range).Distinct();

Using LINQ in C#, How to retrieve list of events based on specific dates, for example all events that are planned for upcoming 45 days?

I am working on this Linq query and it retrieves the list of items from database that are planned for any dates which are greater than the current date.
var todolist = from i in _context.ActPlan
where i.Expected_Date > DateTime.Now
select i;
But i want to retrieve list of the items that are planned for the upcoming 45 days only (all items between the current date and till the upcoming 45 days) but certainly not all future events.
You can use AddDays method (https://learn.microsoft.com/en-us/dotnet/api/system.datetime.adddays?view=netframework-4.7.2)
DateTime inFortyFiveDays = DateTime.Now.AddDays(45);
var toDoList = (from i in _context.ActPlan where
i.Expected_Date > DateTime.Now &&
i.Expected_Date < inFortyFiveDays
select i)

LINQ to entites does not recognize Convert.ToDatetime method

EDIT All the other answers that link to a previous question's wont work for me because they are either using two tables or they know what startdate they are looking for.
I have the following LINQ query where i am trying to get the data from a table for the last 14 days. LINQ does not recognize Convert.ToDatetime method. The Query_Date column is a type string and i can't change it. How do i get the data i need?
var logs = (from bwl in db.UserActivities
where Convert.ToDateTime(bwl.Query_Date) >= DateTime.Now.AddDays(-14)
select new
{
Id = bwl.Id,
UserEmail = bwl.UserEmail
}).ToList();
So i couldn't get what i wanted because i would have to make too many changes so the workaround i am doing is: I am using this code
var logs = db.UserActivities.ToList().Take(100);
This will get me the last 100 entries. I will give options for more or less entries then they can filter it on date in the search bar on the datatable.
It's not great but time is against me and this will suffice.
Do you have data being entered at least every day? If so, what about something like this:
var oldestDate = DateTime.Now.AddDays(-14);
var dateString = oldestDate.ToString(*/ your date format */);
var oldestID = db.UserActivities.First(b => b.Query_Date == dateString).Id;
var logs = (from bwl in db.UserActivities
where bwl.Id > oldestID
select new {
Id = bwl.Id,
UserEmail = bwl.UserEmail
}).ToList();
Basically you find a record on that date and use its ID as a proxy for the date. This only works in certain circumstances (i.e. if the IDs are in date order).
This also isn't guaranteed to be the oldest entry on that date, but that could be achieved either by using ID order:
var oldestID = db.UserActivities.Where(b => b.Query_Date == dateString)
.OrderBy(b => b.Id)
.First().Id;
Or more lazily by using -15 instead of -14 when you add days, if you don't mind grabbing an unknown percentage of that 15th day.
Convert.ToDateTime works if your Query_Date has proper format. If not, check your string expression is convertable format.
I tested below code and it works fine when I assume Query_Date is a form of DateTime.toString().
var logs = (from bwl in db.UserActivities
where DateTime.Now - Convert.ToDateTime(bwl.Query_Date) <= TimeSpan.FromDays(14)
select new
{
Id = bwl.Id,
UserEmail = bwl.UserEmail
}).ToList();
I also tested with your where expression Convert.ToDateTime(bwl.Query_Date) >= DateTime.Now.AddDays(-14) and confirmed that it gives same result.

How can I group a date column to a less precise format while selecting in Entity Framework or LINQ?

I am collecting data within every ten seconds (six records in a minute).
Using Entity Framework or LINQ, I want to obtain the average of the records within a every minute.
Simply, Date column is in (%Y.%m.%d %H:%i:%s) format, and i want to group by (%Y.%m.%d %H:%i) format in mysql using Entity Framework or LINQ
Assuming that you mean you have a date time column you can group by the DateTime properties Year, Month, Day, Hour, and Minute.
var results = from row in db.SomeTable
group by new
{
row.Date.Year,
row.Date.Month,
row.Date.Day,
row.Date.Hour,
row.Date.Minute
} into grp
select new
{
YMDHM = grp.Key
SomeAverage = grp.Average(x => x.SomeValueToAverage)
};
Then when you iterate the results you can turn the values in YMDHM back into a DateTime. Here's an example where you could turn the results into a Dictionary.
var dictionaryOfAverages = results.ToDictionary(
x => new DateTime(x.YMDHM.Year,
x.YMDHM.Month,
x.YMDHM.Day,
x.YMDHM.Hour,
x.YMDHM.Minute,
0),
x => x.SomeAverage);
On the other hand if you actually mean you are storing the date time in the DB as a formatted string then the following would be what you want
var results = from row in db.SomeTable
group by new row.Date.SubString(0, 16) into grp
select new
{
YMDHM = grp.Key
SomeAverage = grp.Average(x => x.SomeValueToAverage)
};
This is assuming that your string formatted dates look like "2013.05.08 07:25:33" If the format isn't fixed width with leading zeros for month, day, and/or hour you'd have to do something like row.Date.SubString(0, row.Date.Length - 3) instead

How to get all records within the last Two Days from the current Date using EF 4?

EF 4 in C#.
I have my query, at the moment I'm able to filter the result by the current Date (just date not considering TIME).
I need to filter the result FROM the last two days TO the current Date (no idea how to do it).
I tried in my query currenteDate - 2 but without success.
Could you please give me an example? Thanks for your time on this.
DateTime currenteDate = DateTime.UtcNow.Date;
var contents = from cnt in context.CmsContents
where cnt.IsPublished == true & cnt.IsDeleted == false & cnt.Date == currenteDate
orderby cnt.ContentId descending
select new { cnt.ContentId, cnt.Title, cnt.TitleUrl, cnt.Date, cnt.TypeContent };
For changing current date you need use currenteDate.AddDays(-2). And use >= instead of == to get all records from 2 days before and till the last record
DateTime currenteDate = DateTime.UtcNow.Date.AddDays(-2);
var contents = from cnt in context.CmsContents
where cnt.IsPublished == true & cnt.IsDeleted == false & cnt.Date >= currenteDate
orderby cnt.ContentId descending
select new { cnt.ContentId, cnt.Title, cnt.TitleUrl, cnt.Date, cnt.TypeContent };
use the compare method from the DateTime-object:
cnt.Date.CompareTo( DateTime.Now.AddDays( -2 ) ) >= 0

Categories

Resources