Filtering by Date (linq) - linq

I have DateTime field named "repeat" in database. I want to take only records which Date in "repeat" is today.
I tried :
(...).Where(e => e.repeat.Value.Date.Day.Equals(DateTime.Now.Day));
or:
(...).Where(e => e.repeat.Value.Date.Day==DateTime.Now.Day);
but it doesn't work.
Any ideas?
Thanks,Kamil

"It doesn't work" is pretty vague, but currently you're checking the day of the week rather than the date. I would suggest using:
Date today = DateTime.Today;
var query = ....Where(e => e.repeat.Value.Date == today);
EDIT: It's not clear what the types involved here are - if repeat.Value is not itself a DateTime, you may want:
var query = ....Where(e => e.repeat.Value.Date.Date == today);

Give this a try:
(...).Where(e => (e.repeat >= DateTime.Today) && (e.repeat < DateTime.Today.AddDays(1)))

Compare short date ensures you the year/month/day are the same in one shot :
(...).Where(e => e.repeat.Value.Date.ToShortDateString() == DateTime.Now.ToShortDateString());

Expert Solution is: Use DbFunctions.CreateDateTime() in Linq Query.
var date = DateTime.Now.AddDays(-1).Date;
var actions = await _context.Set<Your_table>()
.AsNoTracking()
.Where(x => DbFunctions.CreateDateTime(x.YourColumn.Value.Year, x.YourColumn.Value.Month, x.YourColumn.Value.Day, 0, 0, 0) == date)
.ToListAsync();

Related

Compare datetime column just year (without time-day-month) with Linq

I want to get a 2022 records. But my code is not efficient. How to compare it?
> var _year = "2022"; list= query.Where(x =>
> Convert.ToDateTime(x.created_time).ToString("YYYY").Equals(_year
> )).ToList();
Is better not to change type to string, but get DateTime structure Year property.
Code example:
var year = 2022;
var list = query.Where(x => Convert.ToDateTime(x.created_time).Year.Equals(year)).ToList();

Entity Framework: Best way to query for a set of dates using Linq

I have a set of unique DateTimes (without time portion) that the user can select from the user interface. This is not only a range like "LastWeek" or "LastMonth". The user can selcet every single day he wants.
What might be the best way to Linq-query in EntityFramework for matching results? I have a table Foo with an Attribute CreatedAt, which stores information with time portion. Of course I dont want to check the CreatedAt-Property on client side, SqlServer should do the job for me.
I think it should be someting like:
var query = _entities.Foo.Where(x => x.UserID == user.ID);
if (selectedDates.IsNullOrEmpty() == false)
query = query.Where(x => x.CreatedAt 'IsIn' selectedDates);
or:
foreach (var date in selectedDates)
query = query.Where(x => x.CreatedAt.Year == date.Year && x.Month == date.Month && x.Day == date.Month) //but of course here I have the problem that I have to use the 'Or'-Operator, not 'And'.
How can I accomplish this?
You can use EntityFunctions.TruncateTime() to perform a truncation of the date on the server. Then something along the lines of this should work.
query = query.Where(x => selectedDates.Contains(EntityFunctions.TruncateTime(x));
You can call the Contains extension method on selectedDates. Entity Framework 4.0 will understand this and will translate it to an IN operator in SQL:
if (selectedDates.IsNullOrEmpty() == false)
query = query.Where(x => selectedDates.Contains(x.CreatedAt));
Try query = query.Where(x => selectedDates.Contains(x.CreatedAt));

LINQ - how to get next three business days excluding dates in table?

I need to find the next three available business days for a scheduling application. What is available depends upon excluded dates in a table. So...as long as the date is not in my table and not a Saturday or Sunday, I want the next three. I'd like to find an efficient way of doing this.
I need to return a List<DateTime>. The table is simple - ExcludedDates has an ID and a DateTime with the excluded date.
I'd like to have a single LINQ query expression but can't figure it out...thanks to all in advance and I apologize if this is trivial or obvious - it isn't to me.
Try this...
DateTime start = DateTime.Now.Date;
var result = Enumerable.Range(1, 10) // make this '10' higher if necessary (I assume you only exclude non-workingdays like Christmas and Easter)
.Select(offset => start.AddDays(offset))
.Where(date => !( date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek== DayOfWeek.Sunday))
.Where(d=> !exceptionTable.Any(date => date == d))
.Take(3).ToList();
List<DateTime> result = (from i in Enumerable.Range(1, excludeTable.Rows.Count + 6)
let date = inputDate.AddDays(i)
where date.DayOfWeek != DayOfWeek.Saturday &&
date.DayOfWeek != DayOfWeek.Sunday &&
!excludeTable.Rows.Cast<DataRow>().Select(r => (DateTime) r["ExcludeDate"]).Contains(date)
select date).Take(3).ToList();
excludeTable.Rows.Count + 6 is to cover the worst case where you skip over every thing in the excludeTable and then you have to skip over another weekend.
This assumes that a month will be reasonable depending on your excluded dates.
DateTime date = DateTime.Today;
// first generate all dates in the month of 'date'
var dates = Enumerable.Range(1, DateTime.DaysInMonth(date.Year, date.Month)).Select(n => new DateTime(date.Year, date.Month, n));
// then filter the only the start of weeks
var results = (from d in dates
where d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Saturday && !excludes.Any(i => i.DateTime.Date == d.Date) && date < d
select d).Take(3);
var excludedList = new List<long>() { DateTime.Parse("2011-07-27").Ticks };
var week = new List<long>(){
DateTime.Now.Date.Ticks,
DateTime.Now.Date.AddDays(1).Ticks,
DateTime.Now.Date.AddDays(2).Ticks,
DateTime.Now.Date.AddDays(3).Ticks,
DateTime.Now.Date.AddDays(4).Ticks,
DateTime.Now.Date.AddDays(5).Ticks,
DateTime.Now.Date.AddDays(6).Ticks,
DateTime.Now.Date.AddDays(7).Ticks,
DateTime.Now.Date.AddDays(8).Ticks
};
var available = (from d in week.Except(excludedList)
where new DateTime(d).DayOfWeek != DayOfWeek.Saturday && new DateTime(d).DayOfWeek != DayOfWeek.Sunday
select new DateTime(d)).Take(3);
foreach (var a in available)
Console.WriteLine(a.ToString());

BETWEEN EQUIVALENT in LINQ

I am looking LINQ equivalent for the following query
Select * from ct_rate
WHERE
'2010-10-01 00:00:00'
BETWEEN start_date and end_date;
ANY IDEA?
You need to use two comparison operations:
DateTime date = new DateTime(2010, 10, 1);
var results = from rate in ct_rates
where rate.StartDate <= date && rate.EndDate >= date
select rate;
Just use ordinary comparison operators
var result = ct_rates
.Where(x => x.start_date <= myDate && x => x.endDate >= myDate);
In our case, Robert's answer was close to what I was looking for. In our data model, our 'end' or 'through' date columns are nullable.
Something like the following was needed:
Category.Where(
w => w.ValidFrom <= now &&
(w.ValidThru == null ? DateTime.MaxValue : w.ValidThru) >= now).Select(s => s).Dump();
I found this works when wanting only to compare the data part.
var results = from rate in ct_rates
where rate.StartDate.Date <= date && rate.EndDate.Date >= date
select rate;
something like this?
var result = from context.ct_rate.Where(d => d.start_date >= "2010-10-01 00:00:00" && d.end_date <= "2010-10-01 00:00:00")

Compare only Date in nHibernate Linq on a DateTime value

I trying to compare two dates (DateTime) in nHibernate linq:
query = query.Where(l => (l.datCriacao.Date == dtLote.Date)
but I am getting the error:
NHibernate.QueryException: could not resolve property: datCriacao.Date of: SAGP.Entities.Lote
Anyone knows how I can solve this? Thanks
I solved the problem doing a between with the dates:
DateTime initialDate, finalDate;
initialDate= DateEntity.Date;
finalDate= new DateTime(DateEntity.Year, DateEntity.Month, DateEntity.Day, 23, 59, 59);
query = query.Where(l => (((l.dateEntity>= initialDate) && (l.dateEntity<= finalDate))
This is super old, but I'd add to jaspion's example as:
query = query.Where(l => (l.datCriacao >= dtLote.Date && l.datCriacao < dtLote.Date.AddDays(1))
You can check the condition like this
var nextDay = DateTime.Today.AddDays(1);
query = query.Where(l => (l.datCriacao >= dtLote && l.datCriacao < nextDay);
here you'll get the records on dtLote date as we checking between dtLote and dtLote+1 day (00:00:00) we'll get today's date record only what ever may be the time...

Resources