Reputation: 1842
What is the linq equivalent to getting Saturday of the week given a date?
This is what I would do in sql
select trunc(sysdate, 'DAY')+6 from dual
Thank you
Upvotes: 0
Views: 912
Reputation:
It depends on what your LINQ provider supports. Generally speaking, outside of LINQ, you would be able to write it as date.AddDays(6 - (int) date.DayOfWeek)
. This has a reasonable chance of being translatable by a LINQ provider already.
However, for both the AddDays
method and the DayOfWeek
property, it's possible that any specific LINQ provider will require the use of a special function rather than .NET DateTime
's own method and property. There is for instance SqlFunctions.DateAdd
and SqlFunctions.DatePart
for Entity Framework-to-SQL Server. These may also be accepted by other Entity Framework providers.
There's not enough information in your question to know which particular LINQ provider you're using, which is why I'm only answering with general information. If none of these methods and property work for you, you'll have to check the documentation for the particular LINQ provider that you are using.
Upvotes: 1
Reputation: 25377
I don't know what LINQ has to do with it, but you could create a local helper method or even an extension class with a static extension method:
public static class DateTimeExtension
{
public static DateTime Next(this DateTime startDate, DayOfWeek targetDay)
{
do {
startDate = startDate.AddDays(1);
} while (startDate.DayOfWeek != targetDay)
return startDate;
}
}
Then you could do something like:
DateTime nextSaturday = DateTime.Now.Next(DayOfWeek.Saturday);
This could be used with LINQ:
DateTime[] days = new DateTime[] { new DateTime(2015,10,5), new DateTime(2015,9,7)};
var saturdays = from day in days select day.Next(DayOfWeek.Saturday);
Upvotes: 2