I am trying to get the records from database where StartTime field should be today's date.
service.GetAll().Where(o => o.StartTime. == DateTime.Today.Date).Select(o => new SelectableItem(o.Id, o.TestPurpose, v == o.Id))
The date in database is of this format.
2016-07-01 07:00:00.000
How do I compare this format with today's date, I need to compare only date and not the time.
You can use approach specified by #Renan Araujo.
Or another way is, define two dates and use
.Where(o => o.StartTime >= date1 && o.StartTime < date2)
where
date1 = DateTime.Today.Date; // (lets say today's date=10-13-2016 )
date2 = DateTime.Today.AddDays(1).Date; // (tomorrow's date = 10-14-2016)
Use EntityFunctions.TruncateTime to remove the time portion:
service.GetAll()
.Where(o => EntityFunctions.TruncateTime(o.StartTime) == EntityFunctions.TruncateTime(DateTime.Today.Date))
.Select(o => new SelectableItem(o.Id, o.TestPurpose, v == o.Id))
Related
I have a list which contains dates and the same date can be repeated multiple times.
List<DateTime> dates = new List<DateTime>();
foreach (List<string> l in reservations)
{
var start = Convert.ToDateTime(l.First());
var end = Convert.ToDateTime(l.Last());
for (var date = start.Date; date.Date <= end.Date; date = date.AddDays(1))
dates.Add(date);
}
I want to find the date with maximum occurrences. If there are multiple dates with the maximum occurrence, I need to get the earliest date. Here's the LINQ query I wrote:
DateTime max = dates.GroupBy(s => s)
.OrderByDescending(s => s.Count())
.ThenBy(s => s)
.First().Key;
Here I'm getting the error:
At least one object must implement IComparable.'
How do I do this?
#Servy is correct.
I would suggest:
DateTime max = dates.GroupBy(s => s)
.OrderByDescending(sg => sg.Count())
.ThenBy(sg => sg.Key)
.First().Key;
You're trying to order by a group of dates. An entire group of dates can't be compared to another group of dates (unless you supply a custom comparer).
You probably want to order on the group's key, which is a single date, not on the entire group.
I'm trying to add to the dates all the events between Date and DateFinal in order to fill the calendar with the events.
I've already searched but I can't find any solution for this.
pageItems.Add("dates", allEvents.Select(i => i.Date).ToList());
This is what I have so far but only show the days of i.Date and I want to show all of the days between Date and DateFinal.
Cheers and thanks in advance
In the allEvents I have
allEvents = Current.Descendants(n => n.NodeTypeAlias == "EventPage")
.get_Items()
.Select(n => new{
Node = n,
Date = (Helper.ParseXmlDate(n.GetProperty("itemDate")) ?? n.UpdateDate).DatePart(),
DateFinal = (Helper.ParseXmlDate(n.GetProperty("itemDateFinal")) ?? n.UpdateDate).DatePart()
});
Use this:
allEvents.Where(i => i.Date > Date && i.Date < DateFinal).Select(i => i.Date).ToList()
First.. Sorry if I have misunderstood the question
If you have 2 DateTime and you want to select a list of all the Days(as DateTime) between those 2 dates, you could use Enumerable.Range using the amount of days between the Date and DateFinal to loop in your select statement to add a day to the start date and output a list of DateTimes
This will select all the dates between Date and DateFinal.
allevents.Select(i => Enumerable.Range(1, (i.DateFinal - i.Date).Days).Select(dayCount => i.Date.AddDays(dayCount))).ToList()
If you need to include Date and DateFinal to the list you can use
allevents.Select(i => Enumerable.Range(0, 1 + (i.DateFinal - i.Date).Days).Select(dayCount => i.Date.AddDays(dayCount))).ToList()
Input:
Date: 02/20/2013
DateFinal: 02/31/2013
OutPut:
02/20/2013
02/21/2013
02/22/2013
02/23/2013
...
Is that what you mean?
You probably searching for:
TimeSpan span=d2-d1;
span.TotalDays;
so it should look like:
allEvents.Select(i => (DateFinal - i.Date).TotalDays).ToList()
This shows all days between some DateFinal and i.Date
If this is not what you're searching for, please clarify.
Here my current month:
model.SalesForMonth = orders.Where(o => o.DateOfPayment.Value.Month == DateTime.Now.Month)
.Select(o => o.Total)
.Sum();
This is not working as expect as it's also fetching orders that happened last year at the same month.
Sure I could compare year and month, but there must be a more expressive solution I'm not familiar with.
How can I do this cleanly using Linq? (Not sure if relevant but orders is an IQueryable from Entity Framework)
The simplest way would be to create a start and end point:
// TODO: Consider what time zone you want to consider the current date in
var today = DateTime.Today;
var start = new DateTime(today.Year, today.Month, 1);
var end = start.AddMonths(1); // Exclusive end-point
var query = orders.Where(o => o.DateOfPayment.Value >= start &&
o.DateOfPayment.Value < end)
.Sum(o => o.Total)
I'm not sure what you want. You must compare year too to be sure that orders are from this year.
I think you can do it this way with linq:
model.SalesForMonth = orders.Where(o => (o.DateOfPayment.Value.Month == DateTime.Now.Month
&& o.DateOfPayment.Value.Year == DateTime.Now.Year))
.Select(o => o.Total)
.Sum();
I'm using C# 3.5 and EntityFramework. I have a list of items in the database that contain interest rates. Unfortunately this list only contains the Effective Start Date. I need to query this list for all items within a range.
However, I can't see a way to do this without querying the database twice. (Although I'm wondering if delayed execution with EntityFramework is making only one call.) Regardless, I'm wondering if I can do this without using my context twice.
internal IQueryable<Interest> GetInterests(DateTime startDate, DateTime endDate) {
var FirstDate = Context.All().Where(x => x.START_DATE < startDate).Max(x => x.START_DATE);
IQueryable<Interest> listOfItems = Context.All().Where(x => x.START_DATE >= FirstDate && x.START_DATE <= endDate);
return listOfItems;
}
If you could use a LINQ query, you can use let to do this:
(from c in dbContext.Table
let firstdate = dbContext.Table.Max(i => c.StartDate < startDate)
where c.StartDate >= firstdate
and c.StartDate <= enddate
select c)
I'm not sure if the max will work this way, so you may need to alternatively do:
(from c in dbContext.Table
let firstdate = dbContext.Table.Select(i => i.StartDate).Max(i => c.StartDate < i)
where c.StartDate >= firstdate
and c.StartDate <= enddate
select c)
Something like that.
I haven't tried this on EF but on Linq to objects it works fine:
var result = source
.OrderBy(x => x.start)
.GroupBy(x => x.start < startDate)
.SelectMany((x, i) => i == 0 ? new[] {new { value = x.Last().value, start = x.Last().start }} : x.Where(y => y.start < endDate));
The issue is that C# LINQ is missing an operator which gives you access to the previous item in a sequence. F# apparently can handle this. Workarounds involved either a GroupBy or an Aggregate operation. In this case, GroupBy can handle it.
It's not pretty and I wouldn't recommend using it over the two phase approach.
I have a List which contains dates from June 1, 2009 to June 1, 2014. How would I query it in C# LINQ to select only the first date of each month?
Your question is slightly ambiguous. If you want the first item appearing in the list in each month, you can use:
var result = list.GroupBy(x => new { x.Year, x.Month })
.Select(x => x.Min());
The simplest way I think is to filter by the Day property of your dates:
var firstDays = dates.Where(d=> d.Day == 1);
Like this:
dates.Where(d => d.Day == 1);
Or, using query comprehension,
from d in dates where d.Day == 1 select d;
Try the following
public static bool IsFirstDayOfMonth(this DateTime t) {
var other = new DateTime(t.Year,t.Month,1);
return other == t.Date;
}
var allDates = GetTheDates();
var filter = allDates.Where(x => x.IsFirstDayOfMonth());