When "thursdaytime" = Closed <- i want it to skip the next IF
Can't get the "goto" to work.
Sometimes "thursdaytime" is 07:30-16:30 <-- and then the next IF is okay
if (today == DayOfWeek.Thursday && thursdaytime == "Closed")
{
sqlreadclosed();
goto Ended;
}
if (today == DayOfWeek.Thursday && DateTime.Now.TimeOfDay > System.TimeSpan.Parse(thursdaytime.Substring(6, 5)) || DateTime.Now.TimeOfDay < System.TimeSpan.Parse(thursdaytime.Substring(0, 5)))
{
sqlreadclosed();
}
else
{
sqlreadopen();
}
Ended:
Can anyone help me out here.. im a Beginner at C# :)
If its helps, the point is, goto sqlreadclosed() if the clock is under 07:30 or over 16:30 and it works great. but when thursdaytime is "Closed" the under and over IF is crashing.. thats why i want to skip it ,if thursdaytime = Closed
Guess you wanted something like this:
if (today == DayOfWeek.Thursday && thursdaytime == "Closed")
{
sqlreadclosed();
//goto Ended;
}
else if (
today == DayOfWeek.Thursday
&& (
DateTime.Now.TimeOfDay > System.TimeSpan.Parse(thursdaytime.Substring(6, 5))
|| DateTime.Now.TimeOfDay < System.TimeSpan.Parse(thursdaytime.Substring(0, 5))
)
)
{
sqlreadclosed();
}
else
{
sqlreadopen();
}
//Ended:
Generally, using goto in C# is only necessary in very rare cases an it is considered bad practice as it leads to "spaghetti code" (i.e. code that has no clear flow). Therefore, use else if for your second condition.
Furthermore, I believe that you have a problem with your second condition, as the two time checks are mutually exclusive. Therefore, the condition will always evaluate to false. This can be fixed by using parantheses in the correct places. Generally be careful when mixing && and || in the same statement.
Alternatively, you can reformat your code to reduce the complexity and avoid the two calls to sqlreadclosed() (cudos to PJ_pavel):
if (today == DayOfWeek.Thursday)
{
if (
thursdaytime == "Closed"
&& (
DateTime.Now.TimeOfDay > System.TimeSpan.Parse(thursdaytime.Substring(6, 5))
|| DateTime.Now.TimeOfDay < System.TimeSpan.Parse(thursdaytime.Substring(0, 5))
)
)
{
sqlreadclosed();
}
else
{
sqlreadopen();
}
//Ended:
For your specific case:
if (today == DayOfWeek.Thursday) {
if(thursdaytime == "Closed" || (DateTime.Now.TimeOfDay > System.TimeSpan.Parse(thursdaytime.Substring(6, 5)) || DateTime.Now.TimeOfDay < System.TimeSpan.Parse(thursdaytime.Substring(0, 5)))){
sqlreadclosed();
else{
sqlreadopen();
}
}
But as guys said in comments: try to read more about conditional statements usage and don't use GOTO - it's a bad practice.
Try using one boolean variable like 'skipflag'. And avoid using goto statements it is considered bad practice. Goto makes the code complex and harder to read.
if (today == DayOfWeek.Thursday && thursdaytime == "Closed")
{
sqlreadclosed();
skipflag = false;
}
else{
skipflag = true;
}
if(skipflag)
{
if (today == DayOfWeek.Thursday && DateTime.Now.TimeOfDay > System.TimeSpan.Parse(thursdaytime.Substring(6, 5)) || DateTime.Now.TimeOfDay < System.TimeSpan.Parse(thursdaytime.Substring(0, 5)))
{
sqlreadclosed();
}
Else
{
sqlreadopen();
}
}
If it's "thursdaytime == "Closed"" but "today!=DayOfWeek.Thursday" then it skips the first if and goes to the second one which will raise an exception.So your first if should be either:
if (today == DayOfWeek.Thursday || thursdaytime == "Closed")
or:
if (thursdaytime == "Closed")
Related
Code
if(Model.CurrentStatus == 1 || Model.CurrentStatus == 2)
{
//can display those records..
}
else if((Model.CurrentStatus == 3 || Model.CurrentStatus == 4) && Model.Date != null)
{
if(Model.Date <= 30 days)
{
//can display those records..
}
}
I have tried the following code and unable to complete it fully as expected
#Html.Partial("Filter", new IndexModel()
{
Id = Model.Id,
Collection = Model.Collection.Where((a => a.CurrentStatus == 1 || a.CurrentStatus == 2)
&& )
})
How to convert the above if condition to linq in cshtml. Thanks
the else-if relationship is an OR relationship. So simply combine the two lines. the inner nested if inside the else if is an AND relationship. This would go into the second set of parentheses
Collection = Model.Collection.Where
(
(a => a.CurrentStatus == 1 || a.CurrentStatus == 2) ||
((a.CurrentStatus == 3 || a.CurrentStatus == 4) && a.Date != null && a.Date <= 30)
)
EDIT:
Here is another suggestion: extract the readable code into an own method that evaluates the condition and returns the boolean result. This way you can make a predicate that can be accepted by the Where method:
private bool IsForDisplay( ModelDataType Model )
{
if(Model.CurrentStatus == 1 || Model.CurrentStatus == 2)
{
//can display those records..
return true;
}
else if((Model.CurrentStatus == 3 || Model.CurrentStatus == 4) && Model.Date != null)
{
if(Model.Date <= 30 days)
{
//can display those records..
return true;
}
}
return false;
}
now you can use it simply in the linq expression:
#Html.Partial("Filter", new IndexModel()
{
Id = Model.Id,
Collection = Model.Collection.Where(a => IsForDisplay(a))
});
I was playing a little in Unity on a project and I stumbled upon an issue I can't address. Please keep in mind I am a beginner, and my understanding of Unity is fairly limited.
So the issue is this..
I wanted to test some if statement that went like this:
void Update()
{
if (isRow1Good() || isRow2Good() || isRow3Good() || isRow4Good() || isRow5Good() ||
isRow6Good() || isRow7Good() || isRow8Good() || isRow9Good() || isRow10Good())
{
Debug.Log("LOL");
}
}
The content of the functions is this:
Piece p1 = row1[0].ReturnPiece();
Piece p2 = row1[1].ReturnPiece();
Piece p3 = row1[2].ReturnPiece();
Piece p4 = row1[3].ReturnPiece();
if (p1.isTall && p2.isTall && p3.isTall && p4.isTall)
{
return true;
}
else if (p1.isRed && p2.isRed && p3.isRed && p4.isRed)
{
return true;
}
else if (p1.isHollow && p2.isHollow && p3.isHollow && p4.isHollow)
{
return true;
}
else if (p1.isCylinder && p2.isCylinder && p3.isCylinder && p4.isCylinder)
{
return true;
}
else
{
return false;
}
And the others are the same, just instead of row1[] it's row2[].
If the first function is true, the console logs the "LOL" message, but if the second or the third and so on are true, the value is not getting outputted. I tried changing the functions' places, every time it only cares if the first one is true, and the rest are ignored.
What would you say I am doing wrong? :D
else if (p1.isRed && p2.isRed && p3.isRed && p4.isRed)
{
return true;
}
else if (p1.isHollow && p2.isHollow && p3.isHollow && p4.isHollow)
{
return true;
}
else if (p1.isCylinder && p2.isCylinder && p3.isCylinder && p4.isCylinder)
{
return true;
}
if I'm understanding you correct if all four pieces in a row are red its not returning true. You need to double check if the 'isRed' is set properly. if p1.isRed and p2.isRed and p3.isRed and p4.isRed then it will return true no matter what. Also double check if you meant to put || instead of &&.
I am creating an application in C# MVVM. I have a simple question. Is there any possibility to store math operator in variable? I have a code like that:
public ICollectionView FilteredCollection
{
get
{
return filteredCollection;
}
set
{
filteredCollection = value;
OnPropertyChanged("FilteredCollection");
}
}
FilteredCollection.Filter = x => (
(string.IsNullOrEmpty(DynamicSearchEmployeeName) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeName))
&& (DynamicSearchEmployeeID == null || ((Employee)x).EmployeeID == DynamicSearchEmployeeID)
&& (string.IsNullOrEmpty(DynamicSearchEmployeeSalary) || ((Employee)x).EmployeeSalary == Convert.ToInt32(DynamicSearchEmployeeSalary))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeDesigner) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeDesigner))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeEmailID) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeEmailID))
);
What I want to achieve:
In fourth line (DynamicSearchEmployeeSalary) math operator should be depended on following conditions:
if (IsPressedEqual == true)
VARIABLE = "=="
if (IsPressedLess == true)
VARIABLE = "<"
if (IsPressedGreater == true)
VARIABLE = ">"
if (IsPressedLess == true && IsPressedEqual == true)
VARIABLE = "<="
if (IsPressedGreater == true && IsPressedEqual == true)
VARIABLE = ">="
Scenario:
For example I put a value like 10000 in textbox, then click on button with "=" operator. As a result I want to receive Employees with Salary equals than 10000.
Then I click on ">". And I have Employees with Salary greater and equals 10000.
FilteredCollection.Filter = x => (
(string.IsNullOrEmpty(DynamicSearchEmployeeName) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeName))
&& (DynamicSearchEmployeeID == null || ((Employee)x).EmployeeID == DynamicSearchEmployeeID)
&& (string.IsNullOrEmpty(DynamicSearchEmployeeSalary) || ((Employee)x).EmployeeSalary VARIABLE Convert.ToInt32(DynamicSearchEmployeeSalary))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeDesigner) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeDesigner))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeEmailID) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeEmailID))
I've made a simple Rule Based Engine ... I think it will help you in your issue ...
please find it as a nuget package here: https://www.nuget.org/packages/IbnSherien.RuleBasedEngine/
you can create a rule like this:
var rule = RuleEngine.CreateRule<Employee>()
.If<Employee>(e => e.EmployeeSalary).GreaterThan(DynamicSearchEmployeeSalary)
.Validate();
FilteredCollection.Filter = x => (
(string.IsNullOrEmpty(DynamicSearchEmployeeName) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeName))
&& (DynamicSearchEmployeeID == null || ((Employee)x).EmployeeID == DynamicSearchEmployeeID)
&& (string.IsNullOrEmpty(DynamicSearchEmployeeSalary) || rule.Match((Employee)x).IsMatch)
&& (string.IsNullOrEmpty(DynamicSearchEmployeeDesigner) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeDesigner))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeEmailID) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeEmailID))
feel free to add any comments or contribute to the package
This method is taken from Murach's C# 2010 book and is given as an example of an method that checks if a string contains a decimal value:
// the new IsDecimal method
public bool IsDecimal(TextBox textBox, string name)
{
//make sure the string only contains numbers and numeric formatting
string s = textBox.Text;
int decimalCount = 0;
bool validDecimal = true;
foreach (char c in s)
{
if (!(
c == '0' || c == '1' || c == '2' || // numeric chars
c == '3' || c == '4' || c == '5' ||
c == '6' || c == '7' || c == '8' ||
c == '9' || c == '.' ||
c == '$' || c == '%' || c == ',' || // formatting chars
c == ' '
))
{
validDecimal = false;
break;
}
if (c == '.')
{
decimalCount++;
}
} // end loop
if (validDecimal && decimalCount <= 1)
{
return true;
}
else
{
MessageBox.Show(name + " must be a decimal number.",
"Entry Error");
textBox.Focus();
return false;
}
}
My question is about this if statement and boolean value:
if (validDecimal && decimalCount <= 1)
{
return true;
}
I understand that it should be checking if both validDecimal returns true from above loop and that there is only one decimal point present. I'm quite confused by this, my understanding of bool is that it can hold two values: 1 = true and 0 = false; in both of those cases that if statement would be satisfied (0 is smaller than 1 and 1 is equal). I'm thinking that correct if statement would look something like that: if (validDecimal == true && decimalCount <= 1) but since I'm beginner I'm not sure and this isn't in the errata for this book.
A bool value on its own is the same as value == true
If you have
bool trueThing = true;
then the following are all equivalent (and true)
trueThing;
trueThing == true;
(trueThing == true) == true;
((trueThing == true) == true) == true;
and so on. The simplest, least verbose form is the first: trueThing. It's not a 0 or 1, it's a true or false.
Operator Precedence. This:
if (validDecimal && decimalCount <= 1)
is interpreted as:
if (validDecimal && (decimalCount <= 1))
not
if ((validDecimal && decimalCount) <= 1)
In other words, the <= happens before the &&.
I think you're reading the statement wrong, if you placed parentheses, so that it's obvious what's going on, it would look like
(validDecimal) && (decimalCount <= 1)
not
(validDecimal && decimalCount) <= 1
In English: check that validDecimal is true and decimalCount is at most 1. The comparison against true is implicit, because it's not necessary.
In C#, variable of type bool can have one of two values, true or false, but they don't act as numbers, so you can't say they are 1 and 0 (although they are usually implemented that way).
Also, in most languages, if you mean “a and b are both at most x”, you can't write it as a && b <= x. That's just not how (most) computer languages work.
You can write
if (validDecimal == true && decimalCount <= 1)
but it is equivalent to the shorthand way
if (validDecimal && decimalCount <= 1)
When the type is a bool no need to again use
== true
as it is assumed
I don't really know in c#, but in Java, you can even do this:
boolean b = 1<2;
1<2 is true (remember, it's a boolean equation), so the value assigned to b is true. Everything you put in the if, is interpreted as
if(whateverLogicEquationHereIsTrue){do this}
else{means that the boolean input to the if, has come to be false}
now, what is the output of this?
if(!(1>2)){print "a"}
else{print "b"}
hint: ! is the logical operator NOT
Basically I just want to check if one time period overlaps with another.
Null end date means till infinity. Can anyone shorten this for me as its quite hard to read at times. Cheers
public class TimePeriod
{
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; }
public bool Overlaps(TimePeriod other)
{
// Means it overlaps
if (other.StartDate == this.StartDate
|| other.EndDate == this.StartDate
|| other.StartDate == this.EndDate
|| other.EndDate == this.EndDate)
return true;
if(this.StartDate > other.StartDate)
{
// Negative
if (this.EndDate.HasValue)
{
if (this.EndDate.Value < other.StartDate)
return true;
if (other.EndDate.HasValue && this.EndDate.Value < other.EndDate.Value)
return true;
}
// Negative
if (other.EndDate.HasValue)
{
if (other.EndDate.Value > this.StartDate)
return true;
if (this.EndDate.HasValue && other.EndDate.Value > this.EndDate.Value)
return true;
}
else
return true;
}
else if(this.StartDate < other.StartDate)
{
// Negative
if (this.EndDate.HasValue)
{
if (this.EndDate.Value > other.StartDate)
return true;
if (other.EndDate.HasValue && this.EndDate.Value > other.EndDate.Value)
return true;
}
else
return true;
// Negative
if (other.EndDate.HasValue)
{
if (other.EndDate.Value < this.StartDate)
return true;
if (this.EndDate.HasValue && other.EndDate.Value < this.EndDate.Value)
return true;
}
}
return false;
}
}
public bool Overlaps(TimePeriod other)
{
return (other.StartDate >= StartDate &&
(EndDate == null || other.StartDate <= EndDate.Value)) ||
(StartDate >= other.StartDate &&
(other.EndDate == null || StartDate <= other.EndDate.Value))
}
How about this one:
public bool Overlaps(TimePeriod other)
{
bool isOtherEarlier = this.StartDate > other.StartDate;
TimePeriod earlier = isOtherEarlier ? other : this;
TimePeriod later = isOtherEarlier ? this : other;
return !earlier.EndDate.HasValue || earlier.EndDate > later.StartDate;
}
Check this out: DateTimeOverlaps
Very generally, if all variables are nullable datetimes, then
return (StartA.HasValue? StartA.Value:DateTime.Minimum) <=
(EndB.HasValue? EndB.Value:DateTime.Maximum) &&
(EndA.HasValue? EndA.Value:DateTime.Maximum) >=
(StartB.HasValue? StartB.Value:DateTime.Minimum);
The concept, (as explained in link) is very simple, and is simply and concisely expressed above.
If the start is before the others end, and the end is after the other start, you have overlap. This says it all, and all that is necessary, in one simple sentence with two clauses, and whatever code you write should concisely map to that simple concept without obfuscating it. Adding extra unecessary complexity does not add understanding, it only adds length.
Fail Case 1: TopStart AFTER other End - Fail
|----------|
|--|
Fail Case 2: TopEnd AFTER other start - Fail
|-----------|
|------|
In all other cases, start is before other end, and end is after other start.
case A
|----------|
|-----|
case B
| ---------|
|-------------------|
case C
|-----------|
|------|
case D
|-----------|
|-------------|
Any time you're dealing with pure boolean logic, you can distill your algorithm down to a single statement. But don't assume that just because you can, you should. Unless performance is vital, always go for readable code over compact code. (Not that compactness == performance, necessarily)
This is easy to read because it's comprised entirely of single AND expressions, and it's obvious that they all determine a non-overlap:
public bool Overlaps(TimePeriod other)
{
if (other.EndDate.HasValue && other.EndDate < StartDate)
return false;
if (EndDate.HasValue && EndDate < other.StartDate)
return false;
if (!EndDate.HasValue && other.EndDate < StartDate)
return false;
if (!other.EndDate.HasValue && EndDate < other.StartDate)
return false;
return true;
}
Not that the other answers are bad (I like Adam's; his formatting is obviously designed to aid readability). I'm just saying this because it's clear you're a beginner, and I think this is one lesson that isn't heeded enough (I'm guilty). Somebody (I think Martin Fowler) once said something like: "Any fool can write code that a computer understands, but a good programmer can write code that a human understands."