Im having trouble with my multiple AND/OR LINQ query
Current Error is "&& cannot be applied to bool and datetime"
Is there a better way to do this?
I think I may need to check for nulls on some of those too
Thanks
(d.Development != 1 && d.Deleted != 1 && d.Stock != 1) && (d.DecommissionDate = Convert.ToDateTime("1900-01-01"))
The second part doesn't convert to a boolean:
(d.DecommissionDate = Convert.ToDateTime("1900-01-01"))
= is an assignment operator. When it is done, it will try to compare a boolean to a DateTime. If your intent is to compare the DecommissionDate, use == instead. If you really want to assign it, you need to do it on a separate occasion.
You got a small typo: you used the single equals (=, used for assignment) instead of the double equals (==, equality).
Here's the fix:
d.DecommissionDate == Convert.ToDateTime("1900-01-01")
Related
In many places throught app I've seen stuffs like this:
(int)f.Status == something.Status
And this Status property is:
public int? Status { get; set; }
What I am trying to achieve is comparing nullable ints (int?) so that they are equal only if they both have a value and the value is the same. In particular, if they are both null I want them to be identified as not equal.
What is the best way to do that?
I'd suggest using:
f.Status == something.Status
assuming the two properties are either int or int?.
C# will allow you to compare int vs int? without an explicit cast.
For future readers, this answer was written prior to the OP making clear that comparing null to null was expected to return false.
This code is risky and it can give you NullReferenceException if f.Status is null.
You can check first if it has value -> f.Status.HasValue before casting to integer.
You can do this to prevent exception:
if (f.Status.HasValue && f.Status == something.Status)
{
}
I'd suggest rewriting condition into this:
f.Status.HasValue && something.Status.HasValue && f.Status == something.Status
It would prevent you from exceptions.
If any of statuses is just and int and not an int?, then you can omit HasValue check.
Already given answer suggests using simple ==, but it will return true in case both are nulls, opposite to suggested. You have to decide if that's desired behaviour.
As mentioned it could be simplified to
f.Status.HasValue && f.Status == something.Status
in case of both nulls result will be the same.
This question has already been answered, but here's another way of comparing nullable values.
if ((f.Status ?? 0) == something.Status){
//enter code here
}
I've got the following code:
// Here is where we will read in all our values and populate the form with them
lblBenCatX.Text = Convert.ToString(reader["Category"]);
lblBenProvX.Text = Convert.ToString(reader["Provision"]);
txtCommentBox.Text = Convert.ToString(reader["Feedback"]);
ddlDefect1.SelectedValue = Convert.ToString(reader["Network"]);
ddlIssue1.SelectedValue = Convert.ToString(reader["Issue_ID"]);
ddlResolution1.SelectedValue = Convert.ToString(reader["Resolution_ID"]);
ddlDefect2.SelectedValue = Convert.ToString(reader["Network2"]);
ddlIssue2.SelectedValue = Convert.ToString(reader["Issue_ID2"]);
ddlResolution2.SelectedValue = Convert.ToString(reader["Resolution_ID2"]);
The first 3 rows of code; no problem. However, if I have a record with a NULL value, the dropdowns break the code. So, I'm thinking I need to check the field first to make sure it's not NULL. Something like:
if (!Convert.ToString(reader["Network"]) = NULL)
{
ddlDefect1.SelectedValue = Convert.ToString(reader["Network"]);
}
However, that's giving me an error:
The left-hand side of an assignment must be a variable, property or
indexer
Any ideas? This is C# in VS2015 with an Oracle back end, if any of that matters.
In C#, you need to use two equal signs in a row == for equality comparison, not one. One equal sign = is an assignment operator.
if (first == second) { ... }
In your case, though, you would want to use the "not equals" != operator:
if (Convert.ToString(reader["Network"]) != null)
Which is cleaner and slightly more-efficent than this:
if (!(Convert.ToString(reader["Network"]) == null))
Note that I've wrapped the whole inner comparison in parens so the whole statement is being negated; otherwise, it will think you're trying to say !Convert.ToString(reader["Network"]), and, as you pointed out in the comments here, you can't use ! with a string.
That being said, if you're converting to string, then it's better to use string.IsNullOrEmpty() for checking:
if (!string.IsNullOrEmpty(reader["Network"].ToString())))
But the best is probably to just check if the column value is null, rather than converting it to string:
if (!reader.IsDBNull(["Network"]))
= is an assignment operator, used when setting values.
== is an equality operator, which determines whether something is equal to something else.
!= is also an equality operator, opposite to the one above. So, when something is not equal to something else.
So actually, you should be using != in this scenario:
if (Convert.ToString(reader["Network"]) != null)
{
ddlDefect1.SelectedValue = Convert.ToString(reader["Network"]);
}
You have a couple of choices. The first is to check if the value is DBNull which is different than an empty string/null value.
if (!reader.IsDBNull([ordinalPositionOfNetworkInSelectStatement]))
ddlDefect1.SelectedValue = Convert.ToString(reader["Network"]);
See IDataReader.IsDBNull. The only thing is that you need to know the ordinal position of the column you are checking.
The alternative is to check for dbnull in your sql select statement and use a function to return an empty string if it is. The positive side of this approach is you do not have to worry about checking for null in your c# code but I am not sure if it has any negative consequences in your oracle query or view. You can do this with COALESCE.
SELECT Category, Provision, Feedback, COALESCE(Network, '') AS Network /*other columns*/
FROM ... -- rest of the query
disclaimer - my oracle syntax is lacking but COALESCE does exist as a function
I need to set the condition as below code.
_orderStatus = Request.QueryString["order"] != null ? Request.QueryString["order"] : _orderStatus != "" ? _orderStatus : "pending";
Currently the condition only applied to show pending order. How can i change and add to get as below condtion:
if Request.QueryString["order"] != null then
_orderStatus: "pending"
else
_orderStatus: "confirmed"
Thanks
should be like this
_orderStatus = Request.QueryString["order"] != null ? "pending" : "Confirmed";
Additional note to the above answer: Let me copy your requirement to the answer:
if Request.QueryString["order"] != null then _orderStatus: "pending"
else _orderStatus: "confirmed"
Here you need to assign the result to the variable _orderStatus, The conditional operator will do that for you, you need not to do an additional assignment within the operator.
While using conditional operator if.. then can be replaced with ?
and else will be replaced by : and the result will be assigned to
the _orderStatus.
Now look into your code( which included in the answer), and apply the replacements as i said. then you will get the answer like the following:
_orderStatus = Request.QueryString["order"] != null ? "pending" : "Confirmed";
The bets way of checking your query string then, try this
if (!string.IsNullOrEmpty(Request.QueryString["order"]))
_orderStatus = "pending";
else
_orderStatus = "confirmed";
There are multiple ways to do either u can simply check the for null or Empty by using if conditon like this
if (!string.IsNullOrEmpty(Request.QueryString["order"]))
_orderStatus = "pending";
else
_orderStatus = "confirmed";
or you can use conditional expression For reference u can go through this link
For your question u can use this way
_orderStatus = Request.QueryString["order"] != null ? "pending" : "Confirmed";
There's no reason to expect any difference in performance.
In my opinion, the ternary operator should only be used if all three operands are very concise and easy to read. Otherwise I think it has the potential to make code harder to read.
I think a lot of people mis-use this operator by using too much logic into one long line of code. I personally won't use it unless the whole line is less than about 80 characters.
I want to say if this property is (Null OR Equals "" OR contains "ImageNotAvailable") Then go ahead and do something. But when I try to use the code below, I get an object reference error. I was hoping by putting (Publisher.ThumbnailURL == null) at the beginning of the test, the other tests would be ignored, but I get error above.
if ((Publisher.ThumbnailURL == null) | (Publisher.ThumbnailURL == "") | (Publisher.ThumbnailURL.Contains("ImageNotAvailable")))
I can simply split these up into "If Else's" but is there a way to specify that if the first test is null, don't try and figure out the rest of the If statement which will cause it to error
Use || instead of |:
if ((Publisher.ThumbnailURL == null) || (Publisher.ThumbnailURL == "") || (Publisher.ThumbnailURL.Contains("ImageNotAvailable")))
|| Operator
The conditional-OR operator (||) performs a logical-OR of its bool
operands, but only evaluates its second operand if necessary.
Note that you could also use string.IsNullOrEmpty as commented by Raphaƫl Althaus:
if (string.IsNullOrEmpty(Publisher.ThumbnailURL) || Publisher.ThumbnailURL.Contains("ImageNotAvailable"))
Yep, use || to evaluate the expression as early as possible, also, using String.IsNullOrEmpty would make the statement more brief:
if (String.IsNullOrEmpty(Publisher.ThumbnailURL) || (Publisher.ThumbnailURL.Contains("ImageNotAvailable")))
how do i convert follow code to one line if else
if (data.BaseCompareId == 2)
report.Load(Server.MapPath("~/Content/StimulReports/MonthGroup.mrt"));
else
report.Load(Server.MapPath("~/Content/StimulReports/YearGroup.mrt"));
i try this code but did not work
data.BaseCompareId == 2
? report.Load(Server.MapPath("~/Content/StimulReports/MonthGroup.mrt"))
: report.Load(Server.MapPath("~/Content/StimulReports/YearGroup.mrt"));
Try with this instead :
string path = data.BaseCompareId == 2
? "~/Content/StimulReports/MonthGroup.mrt"
: "~/Content/StimulReports/YearGroup.mrt";
report.Load(Server.MapPath(path));
Since report.Load() returns a void, it wont work.
Edited version :
string s = data.BaseCompareId == 2
? "MonthGroup.mrt"
: "YearGroup.mrt";
report.Load(Server.MapPath("~/Content/StimulReports/" + s));
I am assuming report.Load returns a void, hence it "doesn't work". That said, why are you doing this? The first example is perfectly clear.
If you want are going to use ?: here use it so only the part which is actually different is in the branching statement:
string fileName = (data.BaseCompareId == 2) ? "MonthGroup.mrt" : "YearGroup.mrt";
report.Load(Server.MapPath("~/Content/StimulReports/" + fileName));
If you want to use a ternary operator, you can do:
report.Load(data.BaseCompareId == 2 ? Server.MapPath("~/Content/StimulReports/MonthGroup.mrt") : Server.MapPath("~/Content/StimulReports/YearGroup.mrt"));
Or (better):
report.Load(Server.MapPath(data.BaseCompareId == 2 ? "~/Content/StimulReports/MonthGroup.mrt" : "~/Content/StimulReports/YearGroup.mrt"));
(Or you could further exploit the similarity in the two strings, as #helb's answer does.)
As has already been noted, your way doesn't work because you're trying to replace a conditional statement with a conditional expression, and conditional expressions have to have a value. Since report.Load apparently returns void, a conditional expression of the form cond ? report.Load(...) : report.Load(...) doesn't have a value, ergo it doesn't work.
Each of the ways above will work because the conditional expressions in them have values - in the first case, the value will be of the type returned by Server.MapPath; in the second case, the value will be of type string.
As to whether you should do this: there are arguments to be made either way. The original way has the advantage of being clear and simple, but it does involve some (arguably undesirable) repetition. The latter approach above has the advantage of only saying things once and emphasising the intent of the whole statement (to load a report), but it's arguably slightly less clear than the original, depending on how used people are to seeing conditional expressions. YMMV.
This syntax is just for cases where it returns something. So you could do something like:
var path = (data.BaseCompareId == 2) ? "~/Content/StimulReports/MonthGroup.mrt" : "~/Content/StimulReports/YearGroup.mrt";
report.Load(Server.MapPath(path));
This is the most concise I could get for a one-liner...
report.Load(Server.MapPath(string.Format("~/Content/StimulReports/{0}Group.mrt", data.CompareId == 2 ? "Month" : "Year")));
However, it seems you just want to make things look cleaner.
More abstraction between data calls and the conditional logic.
You might want to consider making them separate methods, perhaps on your report object?
if(data.CompareId == 2)
report.LoadStimulReports(ReportGroup.Month);
else
report.LoadStimulReports(ReportGroup.Year);
Using an enum, extension method, and static method on your report object...
public enum ReportGroup
{
[DescriptionAttribute("~/Content/StimulReports/MonthGroup.mrt")]
Month,
[DescriptionAttribute("~/Content/StimulReports/YearGroup.mrt")]
Year
}
public static T GetAttribute<T>(this Enum e) where T : Attribute
{
System.Reflection.FieldInfo fi = e.GetType().GetField(e.ToString());
object[] o = (object[])fi.GetCustomAttributes(typeof(T), false);
return o.Length > 0 ? (T)o[0] : default(T);
}
public static void LoadStimulReports(ReportGroup reportGroup)
{
report.Load(Server.MapPath(reportGroup.GetAttribute<DescriptionAttribute>().Description));
}
Now you can simply add another item to the enum if you need another report.
[DescriptionAttribute("~/Content/StimulReports/WeekGroup.mrt")]
Week