C# Handling Else Condition Within Nested Ifs - c#

I need to execute an else statement from a if, and another if inside it.
if (!BoxA_IsNull && !BoxB_IsNull && !BoxC_IsNull && !BoxD_IsNull) //Scenario 1
{
if (BoxA == BoxB && BoxC == BoxD) //Scenario 2
{
//Do something
}
}
else
{
// Do something else if
// 1) Scenario 1 hits but not scenario 2
// 2) Scenario 1 does not hit
}
May I know how can I go to else statement regardless if scenario 1 or scenario 2 hits?
Edit: Apologies on scenario confusion. Have edited as above in else statement
At the end I went with the following solution of
if ((!BoxA_IsNull && !BoxB_IsNull && !BoxC_IsNull && !BoxD_IsNull) && (BoxA == BoxB && BoxC == BoxD))
{
//do something
}
Reason is because during if, it will hit 2nd comparison check if 1st null check fails. The purpose of my 1st null check is to prevent null exception during 2nd comparison check.

Store the conditions in boolean variables. Then you can reuse them.
bool nullCondition = !BoxA_IsNull && !BoxB_IsNull && !BoxC_IsNull && !BoxD_IsNull;
bool equalityCondition = BoxA == BoxB && BoxC == BoxD;
if (nullCondition && equalityCondition)
{
// Both conditions are true
}
else
{
// Any of equalitycondition or nullcondition is false
}

You could store the scenarios in two boolean variables, which makes the check more easily:
bool scenario1 = !BoxA_IsNull && !BoxB_IsNull && !BoxC_IsNull && !BoxD_IsNull;
bool scenario2 = BoxA == BoxB && BoxC == BoxD
if (scenario1)
{
if (scenario2)
{
//do something
}
}
if((scenario1 && !scenario2) || !scenario1)
{
//do something else if either Scenario 1 or 2 hits.
}
Depending on what you are doing exactly, you could also give the variables more expressive names.

I'm not sure I'm understanding you question correctly; the logic you seem to want with your example is pretty simple:
if (!BoxA_IsNull && !BoxB_IsNull && !BoxC_IsNull && !BoxD_IsNull)
{
if (BoxA == BoxB && BoxC == BoxD)
{
//Scenario 1 & 2
}
else
{
//Scenario 1 hits but not scenario 2
}
}
else
{
//Scenario 1 does not hit
}

Related

How to write better else if condition by using less AND and OR logical operator?

I have Client group logo and Client site logo. And want to assign Client site logo a value based on certain conditions.
This is my code in ClientController.cs :
if (site.ImageURL != null && site.ImageURL != "" && clientGroupImage != "/Content/Images/ClientLogoDefault.svg"
&& site.ImageURL != "/Content/Images/ClientSiteLogoDefault.svg" || site.ImageURL != null
&& site.ImageURL != "" && clientGroupImage == "/Content/Images/ClientLogoDefault.svg"
&& site.ImageURL != "/Content/Images/ClientSiteLogoDefault.svg")
{
model.SiteLogoURL = site.ImageURL;
}
else if (site.ImageURL == "/Content/Images/ClientSiteLogoDefault.svg"
&& clientGroupImage != "/Content/Images/ClientLogoDefault.svg" || site.ImageURL == ""
&& clientGroupImage != "/Content/Images/ClientLogoDefault.svg")
{
model.SiteLogoURL = clientGroupImage;
}
else
{
model.SiteLogoURL = "/Content/Images/ClientSiteLogoDefault.svg";
}
So is there a way to write this code using less "&&" and "||" operators?
There are a few ways you can do this;
By writing boolean function for complex conditions, separate complex conditions from code to improve readability and ease of use. You can also re-use these functions for other similar scenarios.
In your case, extract out string literals into variable or const strings. They will be easier to manage easier to read/use. Like Zaven Suggested.
Nesting conditions when for cases there is common condition. Nesting is similar to if-then lingo.
bool client = clientGroupImage == "/Content/Images/ClientLogoDefault.svg";
bool site = site.ImageURL == "/Content/Images/ClientSiteLogoDefault.svg";
if (!string.IsNullOrEmpty(site.ImageURL) && (!client && !site || client && !site)
{
model.SiteLogoURL = site.ImageURL;
}
else if (!client && (site || site.ImageURL == "")
{
model.SiteLogoURL = clientGroupImage;
}
else
{
model.SiteLogoURL = "/Content/Images/ClientSiteLogoDefault.svg";
}
Your conditional statements are not entirely clear, but in general you could treat compounded conditional statements (with AND and OR) a bit like math operators.
For example, in math you can do this: A*B + A*C = A*(B+C)
Now let treat A,B,C as simple conditions and assume * is AND and + is OR.
So if ((A && B) OR (A && C)) can also be if (A && (B OR C))
For your specific case, I would need some clarifications about the first if statement, but I think you can do something like:
if (!string.IsNullOrEmpty(site.ImageURL) && site.ImageURL != "/Content/Images/ClientSiteLogoDefault.svg" &&
(clientGroupImage != "/Content/Images/ClientLogoDefault.svg" || clientGroupImage == "/Content/Images/ClientLogoDefault.svg"))
Seeing as the only difference is clientGroupImage condition, which if you notice will cover all cases, so you can drop this entirely.

This function can only be invoked from LINQ to Entities. .All()

I have a List property that I am setting like so:
testCard.LstSummaries =
db.Summaries.Where(
x =>
(x.AID == aId || x.AInformation.RegNumber == aRegNumber) && DbFunctions.TruncateTime(x.Day) == DateTime.Today.Date &&
x.deleted == false).ToList();
Then I have a conditional statement:
if (testCard.LstSummaries.Count > 0)
{
if (
testCard.LstSummaries.All(
x =>
(x.AID == aId || // ERROR HAPPENS ON THIS LINE
x.AInformation.RegNumber == aRegNumber) &&
DbFunctions.TruncateTime(x.Day) == DateTime.Today.Date && x.deleted == false))
{
// .... do something
}
I get an error:
This function can only be invoked from LINQ to Entities.
I want to avoid to make multiple calls to the database.. furthermore testCard.LstSummaries already has the values I am looking for.. but if I do this:
if (testCard.LstSummaries.Count > 0)
{
if (
db.Summaries.All(
x =>
(x.AID == aId || // NO ERROR
x.AInformation.RegNumber == aRegNumber) &&
DbFunctions.TruncateTime(x.Day) == DateTime.Today.Date && x.deleted == false))
{
// .... do something
}
I feel like making this call to the database is pointless because I would be retrieving the same results that are already stored in testCard.LstSummaries, but I can't invoke .All() because it's not LINQ to Entities.
Is there a workaround for this?
Problem is with DbFunctions.TruncateTime(x.Day), because it is converted to sql on runtime. Try to check without it.

IF ELSE Statement under LINQ's WHERE clause

where task.RevisionDateTime > startDateTime_
&& task.RevisionDateTime <= endDateTime_
&& task.AutoAuditNotes.ToLower() != auditString.ToLower()
&& (if(isStaging_) condition1 else condition2)
select task).ToList();
Under where clause I have this IF ELSE Statement && (if(isStaging_) condition1 else condition2). How can I Add condition under WHERE clause defends on the value of isStaging_ variable?
Thanks.
You can do something like this :
where task.RevisionDateTime > startDateTime_
&& task.RevisionDateTime <= endDateTime_
&& task.AutoAuditNotes.ToLower() != auditString.ToLower()
&& ((isStaging_ && condition1) || condition2)
select task).ToList();
This isn't a direct answer - I upvoted KiNeTiC's answer. But this comment requires some code formatting that can't go into a comment.
This will become much more readable if you break conditions into separate functions. For example, whatever this is:
&& ((isStaging_ && condition1) || condition2)
Put it in its own function with a name describing what it's checking. The branching will make it difficult for someone to read and follow, even the person who wrote it a week later. But if it's a function call then the name of the function serves as a comment.
Long LINQ queries are oddly satisfying to write, but it can be very difficult for someone else to understand what they're doing.
you try
if(isStaging_)
{
//condition1
where task.RevisionDateTime > startDateTime_
&& task.RevisionDateTime <= endDateTime_
&& task.AutoAuditNotes.ToLower() != auditString.ToLower()
select task).ToList();
}
else
{
//condition2
where task.RevisionDateTime > startDateTime_
&& task.RevisionDateTime <= endDateTime_
&& task.AutoAuditNotes.ToLower() != auditString.ToLower()
select task).ToList();
}

Is it proper to negate an entire if statement to check for null values?

I am somewhat of a beginner programmer. What I am trying to do here is to check that if there is a time, if it is selected, and if that time is equivalent to the other. If that is all true then I want to skip the block of code under it. Here is the code example:
if (currentGVR.Round_Start_Time)
{
if (tr.StartLunchDateTime != null && currentGVR.Round_Start_Lunch && roundedStart == roundedStartL)
// skip
else
{
key = tr.TransactionID;
TransactionRecords[key]["Start_DateTime"] = roundedStart;
}
}
I thought about using an OR operator, but I can see where an error would occur if there was no time to compare to. Using the AND operator avoids this dilemma here.
So the overall question is, is it proper coding to negate all of the conditions to get the correct result, e.g. if (!( cond's )), and also, would this be the best way to check if there is a value to compare with before actually comparing it in C# and otherwise? The times can be null (or do not exist) in some records. Any recommendations?
I'd negate all those conditions and switch the && to || so it's more quickly evident under what conditions the code will (or will not) execute.
Plus (in my experience), you don't typically see an empty if block with all the code under the else.
if (tr.StartLunchDateTime == null || !currentGVR.Round_Start_Lunch || roundedStart != roundedStartL)
{
key = tr.TransactionID;
TransactionRecords[key]["Start_DateTime"] = roundedStart;
}
The statement
if (tr.StartLunchDateTime != null && currentGVR.Round_Start_Lunch && roundedStart == roundedStartL){
// skip
}
else
{
key = tr.TransactionID;
TransactionRecords[key]["Start_DateTime"] = roundedStart;
}
is equivalent to
if (!(tr.StartLunchDateTime != null && currentGVR.Round_Start_Lunch && roundedStart == roundedStartL))
{
key = tr.TransactionID;
TransactionRecords[key]["Start_DateTime"] = roundedStart;
}
else {
// skip
}
This can be further simplified because
!(tr.StartLunchDateTime != null &&
currentGVR.Round_Start_Lunch &&
roundedStart == roundedStartL)
Is the same as
(!(tr.StartLunchDateTime != null) ||
!(currentGVR.Round_Start_Lunch) ||
!(roundedStart == roundedStartL))
or
(tr.StartLunchDateTime == null ||
!currentGVR.Round_Start_Lunch ||
roundedStart != roundedStartL)
See DeMorgan's Laws.
if (someLongCondition)
{ }
else
{
doStuff();
}
is equivalent to this:
if (!someLongCondition)
{
doStuff();
}
So yeah, you can just negate your whole condition:
if (!(tr.StartLunchDateTime != null && currentGVR.Round_Start_Lunch && roundedStart == roundedStartL))
{ … }
But you can also pull the negation in (applying De Morgan's laws) and write it like this:
if (tr.StartLunchDateTime == null || !currentGVR.Round_Start_Lunch || roundedStart != roundedStartL)
{ … }
All these are equivalent so choose whatever makes the condition more clear (actually, consider storing it in a separate variable which you give a descriptive name).

|| ,| , && inside an IF statement

i want to do the following IF statement,
if (checkID.Equals(Convert.ToInt32(txtCheck.Text))
&& drop == 319020000
|| currentFloor[id][0].checkFlag == 1)
what i want to check here it the following thing:
i want to check if this whole statement is true
checkID.Equals(Convert.ToInt32(txtCheck.Text)) && drop == 319020000`
or this statment:
currentFloor[id][0].checkFlag == 1
If 1 of them is true it should go inside the loop.
What am i doing wrong here?
Use parentheses, you have many operators at the same level and precedence may be killing you
if ((checkID.Equals(Convert.ToInt32(txtCheck.Text)) && drop == 319020000)
|| currentFloor[id][0].checkFlag == 1)
http://msdn.microsoft.com/en-us/library/aa691323(v=vs.71).aspx
;)
you have to use additional parentheses like follows,
if ((checkID.Equals(Convert.ToInt32(txtCheck.Text)) && drop == 319020000) || currentFloor[id][0].checkFlag == 1)

Categories