This question already has answers here:
Linq Query keeps throwing "Unable to create a constant value of type System.Object....", Why?
(5 answers)
Closed 8 years ago.
I'm trying to create an API method, which will allow to filter entries by date. I want to let to use two parameters - startDate and endDate. The second of them optional.
public IEnumerable<Recommendation> GetRecommendationByDate(DateTime startDate, DateTime? endDate)
{
if (endDate == null)
{
endDate = DateTime.Now;
}
var output = db.Recommendations.Where(r => r.IsPublished == true &&
r.CreatedDate.CompareTo(startDate) > 0 &&
r.CreatedDate.CompareTo(endDate) < 0)
.ToList();
return output;
}
After I've added nullable sign, method thows an exception when the second parameter (endDate) isn't null. When it is null, there is not any problems.
Exception sounds:
Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context.
What is the reason and how to solve it?
Add .HasVale and check if endDate contains the value or not and if it does then use as endDate.Value as shown below
public IEnumerable<Recommendation> GetRecommendationByDate(DateTime startDate, DateTime? endDate)
{
if (endDate == null)
{
endDate = DateTime.Now;
}
var output = db.Recommendations.Where(r => r.IsPublished == true &&
r.CreatedDate.CompareTo(startDate) > 0 &&
r.CreatedDate.CompareTo(endDate.HasValue ? endDate.Value : (The default you want to put when endDate is null)) < 0)
.ToList();
return output;
}
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
I need Lambda query to filter dates from list and return Max Date. If the list does not satisfy the filter then should return a null value. This is my code, need a shorter version ->
var a = Dates.Where(x => x >= DateTime.Now).Select(x => x);
if(a.Count > 0)
{
return a.Max();
}
else return null;
The value returned to is in DateTime? format which shows error "Embedded statement cannot be a declaration or labeled statement".
var Dates = new List<DateTime>();
DateTime? max = Dates.Where(x => x >= DateTime.Now)
.Select(x => (DateTime?) x)
.DefaultIfEmpty(null)
.Max();
Console.WriteLine(max == null ? "null" : "not null");
You need to cast the result to Nullable<DateTime> one way or another, if your list is composed of DateTime.
Edit : as #RogerStewart mentioned in comments, to perform the cast you could use Cast<DateTime?>() instead of the Select statement.
I am using the following code in order to substract a day of the DateTime until I am getting Monday:
DateTime currentWeek = new DateTime(beginDate.Year, beginDate.Month, beginDate.Day);
while (currentWeek.DayOfWeek.ToString() != "Monday")
{
currentWeek.AddDays(-1);
MessageBox.Show(currentWeek.Day.ToString());
MessageBox.Show(currentWeek.DayOfWeek.ToString());
}
beginDate is in the first run set to the current Date of DateTime.Now.
For me this loops forever, and the day of currentWeek always stays the same (29) even though I am substracting 1 everytime I am looping through.
I am already using another function that takes a DateTime and a bool Parameter, which does pretty much the same and works:
private void ErstenTagDerWocheAuswaehlen(DateTime date, bool anfangDerWoche = true)
{
string wochentagName;
int incrementor;
if(anfangDerWoche == true)
{
wochentagName = "Monday";
incrementor = -1;
}
else
{
wochentagName = "Friday";
incrementor = 1;
}
while(date.DayOfWeek.ToString() != wochentagName)
{
date = date.AddDays(incrementor);
}
}
Can someone explain to me why the upper code doesn't work whilst the lower one does?
You have to assign the resulting value, DateTime is immutable.
currentWeek = currentWeek.AddDays(-1);
About your 2nd question:
Use the enum for day of the week, do not try to convert a day of the week to a string for a comparison. The type is DayOfWeek.
Again, a DateTime is not mutable so you have to return a DateTime instance as you can't mutate the one that was passed in (without passing it as ref)
Code change
private DateTime ErstenTagDerWocheAuswaehlen(DateTime date, bool anfangDerWoche = true)
{
System.DayOfWeek wochentagName;
int incrementor;
if(anfangDerWoche == true)
{
wochentagName = System.DayOfWeek.Monday;
incrementor = -1;
}
else
{
wochentagName = System.DayOfWeek.Friday;
incrementor = 1;
}
while(date.DayOfWeek != wochentagName)
{
date = date.AddDays(incrementor);
}
return date;
}
DateTime is an immutable struct, so you need to store the value returned from AddDays():
var t2 = currentWeek.AddDays(-1);
Then use t2. The call to AddDays() doesn't actually change currentWeek.
As DateTime is immutable, when using the AddDays it returns a new DateTime structure with the new information and does not change the given one.
Method documentation states:
Returns a new System.DateTime that adds the specified number of days to the value of this instance.
You must assign it to a variable:
currentWeek = currentWeek.AddDays(-1);
I want to do something if the day, and time of the day equal true in a if statement. I have the day part down, just can't figure out the time part out. Let say I wan the time to be 9AM.
Here is what I have so far
var dt_check_monday = DateTime.Now.DayOfWeek;
if (dt_check_monday == DayOfWeek.Monday && time_now = DateTime.Now.Hour==9)
{
//do something
}
I can't use this I get an error:
Operator '&&' cannot be applied to operands of type 'bool' and 'System.TimeSpan'
Thanks for any help in advance.
= is an assignment. == is the 'equals'
Your second = should be a ==
You should just do this:
if (DateTime.Now.DayOfWeek == DayOfWeek.Monday && DateTime.Now.Hour == 9)
{
}
Your code has an assignment to an undeclared variable time_now and you're doing an assignment time_now = which is what's causing it to fail.
You should also consider revising how you name your variables, dt_check_monday means absolutely nothing if the value inside it is DayOfWeek.Wednesday, consider changing it to something like dt_currentDayOfWeek but that already exists in the form of DateTime.Now.DayOfWeek which is why I dropped the variable from my example.
I think time_now is having TimeSpan datatype. So you can try this
if (dt_check_monday == DayOfWeek.Monday && time_now.Hours == 9)
{
//do something
}
If you want to keep time_now for later use, you have to encase the assignment in the if-statement with paratheses.
var dt_check_monday = DateTime.Now.DayOfWeek;
if (dt_check_monday == DayOfWeek.Monday && (time_now = DateTime.Now.Hour) == 9)
{
//do something
}
I have this block of code that eventually get serialized to JSON, for use in the Jquery FullCalender plugin. The ToUnixTimeSpan method taskes in a DateTime object and returns the number of seconds since 1970.
DateEnd could be null. In this block of code how do i test for the null and skip the end = ToUnixTimespan(e.DateEnd), if DateEnd is null? is there a C# equivalent to the groovy safe operator?
var listEvents = from e in eventRepository.GetAllEvents()
select new
{
id = e.EventID,
title = e.EventTitle,
start = ToUnixTimespan(e.DateStart),
end = ToUnixTimespan(e.DateEnd),
url = "/Events/Details/" + e.EventID
};
Further info about the ToUnixTimespanMethod:
private long ToUnixTimespan(DateTime date)
{
TimeSpan tspan = date.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0));
return (long)Math.Truncate(tspan.TotalSeconds);
}
Well, how about:
end = e.DateEnd == null ? (long?) null : ToUnixTimespan(e.DateEnd)
It's hard to say for sure as we don't know the type returned by ToUnixTimespan.
Wait-a-minute... Why am I wasting this on a comment, when I could be leveraging Jon's work for some rep.. ;-)
end = e.DateEnd == null ? (long?) null : ToUnixTimespan(e.DateEnd.Value)
That should solve the "cannot convert from 'System.DateTime?' to 'System.DateTime'." error.
I am new to c#. I am comparing two dates where one is entered by user and the other one is sytem date time. i have the code working as it stands where the obstacle has occured is how to cater for null values. the basic code I have is:
if (mydate.ToShortDateString() != TodaysDate.ToShortDateString())
{
//Error Messaage
}
else
{
//do some code
}
Any feedback will be appreciated
Why are you converting them to strings? Why not just compare the date portions of them as in date1.Date != date2.Date.
You can declare mydate as DateTime?, then it can hold null values.
As to how to handle the error, it depends on whether having a null value for mydate is considered an error or not. If it's an error, you could do:
if (mydate == null || mydate.ToShortDateString() != TodaysDate.ToShortDateString()) {
// error
}
If it's not an error condition, you could do:
if (mydate != null && mydate.ToShortDateString() != TodaysDate.ToShortDateString()) {
// error
}
If you don't declare mydate as DateTime? but instead just declare it as DateTime, then you can check for DateTime.MinValue, like this (DateTime.MinValue is the default value for a DateTime variable):
if (mydate == DateTime.MinValue || mydate.ToShortDateString() != TodaysDate.ToShortDateString()) {
// error
}
Use the ?? operator:
if ((mydate??DateTime.MinValue).ToShortDateString() != TodaysDate.ToShortDateString())
{
//Error Messaage
}
else
{
//do some code
}