BETWEEN EQUIVALENT in LINQ - 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")

Related

Filtering by Date (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();

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

How to get a group ordered by the count column

It is hard to ask the question in plain english so I'll show what I'm trying to do.
Here's my SQL code:
select top 100 [Name], COUNT([Name]) as total from ActivityLog
where [Timestamp] between '2010-10-28' and '2010-10-29 17:00'
group by [Name]
order by total desc
I need to write that in LinQ. So far I have the following:
var groups = from ActivityLog log in ctx.ActivityLog
where log.Timestamp > dateFrom
where log.Timestamp <= dateTo
group log by log.Name;
but I don't have the COUNT(*) column to sort from :(
I'm afraid I am far more comfortable with the fluent syntax (as opposed to query syntax), but here is one possible LINQ answer:
ctx.ActivityLog
.Where(x => x.TimeStamp > dateFrom && x.TimeStamp <= dateTo)
.GroupBy(x => x.Name)
.Select(x => new { Name = x.Key, Total = x.Count() })
.OrderByDescending(x => x.Total)
.Take(100)
EDIT:
Alright, I stepped out of my comfort zone and came up with a query syntax version, just don't expect too much. I warned you about my abilities above:
(from y in (
from x in (
from log in ActivityLog
where log.Timestamp > dateFrom
where log.Timestamp <= dateTo
group log by log.Name)
select new { Name = x.Key, Total = x.Count() })
orderby y.Total descending
select new { Name = y.Name, Total = y.Total }).Take(100)
diceguyd30's answer technically is LINQ and is correct. In fact, the query syntax gets translated to those Queryable/Enumerable methods by the compiler. That said what's missing is using the group ... by ... into syntax. The equivalent query should be close to this:
var query = from log in ctx.ActivityLog
where log.TimeStamp > dateFrom && log.TimeStamp <= dateTo
group log by log.Name into grouping
orderby grouping.Count() descending
select new { Name = grouping.Key, Total = grouping.Count() };
var result = query.Take(100);
Note that in C# the Take(100) method has no equivalent in query syntax so you must use the extension method. VB.NET, on the other hand, does support Take and Skip in query syntax.

Simplifying LINQ query?

I use this LINQ query in an app I am writing:
internal int GetNoteCount(DateTime startDate, DateTime endDate)
{
var a = DataStore.ObjectContext.Notes.Where(n => n.LastRevised >= startDate);
var b = a.Where(n => n.LastRevised <= endDate);
return b.Count();
}
Obviously, the query gets Notes that fall between two dates. I'd like to simplify the query by consolidating the first two lines into one. I know I can use fluent syntax to add the Count() method call to the end of my query.
Here's my question: How can I consolidate the two queries? Apparently, the && operator doesn't work with two lambda expressions. Thanks for your help.
You can do this:
internal int GetNoteCount(DateTime startDate, DateTime endDate)
{
return DataStore.ObjectContext.Notes.Where(n => n.LastRevised >= startDate && n.LastRevised <= endDate).Count();
}
Just use the && on your conditions, not the entire lambda :)
First, there's nothing wrong with the && operator and it should work just fine.
var a = DataStore.ObjectContext.Notes.Where(n => n.LastRevised >= startDate && n.LastRevised <= endDate);
return a.Count();
Second, with LINQ, it delays performing the query until the .Count() so there is no functional difference between your example and this one.

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