How Can i check if it's the first iteration in my while loop in C#?
while (myCondition)
{
if(first iteration)
{
//Do Somthin
}
//The rest of the codes
}
bool firstIteration = true;
while (myCondition)
{
if(firstIteration )
{
//Do Somthin
firstIteration = false;
}
//The rest of the codes
}
You could move the do something out of the loop. Only guaranteed to do the exact same if the "Do Somthin" does not change myCondition. And myCondition test is pure, i.e. no side effects.
if (myCondition)
{
//Do Somthin
}
while (myCondition)
{
//The rest of the codes
}
use a counter:
int index = 0;
while(myCondition)
{
if(index == 0) {
// Do something
}
index++;
}
You could make a bool outside the loop
bool isFirst = true;
while (myCondition)
{
if(isFirst)
{
isFirst = false;
//Do Somthin
}
//The rest of the codes
}
Something like this?
var first=true;
while (myCondition)
{
if(first)
{
//Do Somthin
}
//The rest of the codes
first=false
}
Define a boolean variable:
bool firstTime = true;
while (myCondition)
{
if(firstTime)
{
//Do Somthin
firstTime = false;
}
//The rest of the codes
}
You can do that by workarounds, like:
boolean first = true;
while (condition)
{
if (first) {
//your stuff
first = false;
}
}
Try something like this:
bool firstIteration = true;
while (myCondition)
{
if(firstIteration)
{
//Do Something
firstIteration = false;
}
//The rest of the codes
}
I would recommend using counter variable for this, or a for loop.
E.G.
int i = 0;
while (myCondition)
{
if(i == 0)
{
//Do Something
}
i++;
//The rest of the codes
}
Still learning, but this way came to me, have not used this before myself but I plan to test and possibly implement in my project:
int invCheck = 1;
if (invCheck > 0)
{
PathMainSouth(); //Link to somewhere
}
else
{
ContinueOtherPath(); //Link to a different path
}
static void PathMainSouth()
{
// do stuff here
}
static void ContinueOtherPath()
{
//do stuff
}
Related
I am trying to find a code that helps to create a pattern of:
but the number of rows and columns are custom.
Currently this is the code I have but it doesnt apply properly for all values.
(labelseat.backcolour=color.red , refers to the red boxes)
count=0;
if (Row%2==0)
{
count+=1;
if (count==3)
{
labelSeat.BackColor=Color.Red;
}
else if (count==4)
{
labelSeat.BackColor=Color.Red;
count=0;
}
}
if (Row%2==1)
{
count+=1;
if (count==1)
{
labelSeat.BackColor=Color.Red;
}
else if (count==2)
{
labelSeat.BackColor=Color.Red;
}
else if (count==4)
{
count=0;
}
}
Maybe something like this:
private void ColorBox(int elementNumber)
{
boolean colorRed = ((int)elementNumber/2) % 2 == 0;
Box[elementNumber].backgroundColor = colorWhite ? "#FF0000" : "#FFFFFF";
}
I have a WPF triggered (TextChanged) function which calls two other function whose subroutine deletes rows from a DataGrid object when certain conditions are met.
I have a feeling I might be encountering race conditions on the delete of multiple rows. When I place a MessageBox.Show("somethings'); in between the two functions, 2 rows from DataGrid are deleted as expected with the message box popping up in between delete actions.
deleteFunction("item1");
MessageBox.Show("something");
deleteFunction("item2");
However if I remove the MessageBox only the first function deletes a single row (item1)from DataGrid.
deleteFunction("item1");
deleteFunction("item2");
I have tried all sorts of ways to resolve this, Thread.Sleep(500) in between function calls, setting up a Queue to FIFO the requests, thread locking. async ... Nothing seems to work for me.
I'm not even sure it is actually a race condition issue anymore. I am starting to wonder if there is some Thread connection to the DataGrid object that the MessageBox is severing when invoked and releasing the control for another function to interact with.
Code below:
private void streamCode_TextChanged(object sender, TextChangedEventArgs e)
{
if (configurationSectionLoaded == true)
{
streamCodeAlphanumeric(streamCode.Text);
streamCodeIsChar128(streamCode.Text);
}
formEdited = true;
}
private bool streamCodeAlphanumeric(string value)
{
dataValidation dv = new dataValidation();
if (dv.isAlphanumeric(value))
{
streamCode.Background = Brushes.LightGreen;
editStreamcode.Background = Brushes.LightGreen;
editStreamcode.IsEnabled = true;
//MessageBox.Show("scE01 Deleting");
//q.Enqueue(new UILogDeleteQueue() { qEntryType = "scE01" });
try
{
UILogRemoveRow("scE01");
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
return true;
}
else
{
editStreamcode.IsEnabled = false;
streamCode.Background = Brushes.LightPink;
UILogAddRow("scE01", "Stream Code", "Non-Alphanumeric Characters Detected!");
return false;
}
}
private bool streamCodeIsChar128(string value)
{
dataValidation dva = new dataValidation();
if (dva.isChar128(value))
{
streamCode.Background = Brushes.LightGreen;
editStreamcode.Background = Brushes.LightGreen;
editStreamcode.IsEnabled = true;
//MessageBox.Show("scE02 Deleting");
try
{
UILogRemoveRow("scE02");
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
return true;
}
else
{
editStreamcode.IsEnabled = false;
streamCode.Background = Brushes.LightPink;
UILogAddRow("scE02", "Stream Code", "Invalid Length Detected!");
return false;
}
}
Finally here is the delete row code:
private void UILogRemoveRow(string entryCode)
{
int rowCount;
rowCount = UILog.Items.Count;
if (rowCount > 0)
{
for (int i = 0; i < rowCount; i++)
{
DataGridRow row = (DataGridRow)UILog.ItemContainerGenerator.ContainerFromIndex(i);
var selectedItem = UILog.ItemContainerGenerator.ContainerFromIndex(i);
if (row != null)
{
UILogObject theItem = (UILogObject)row.DataContext;
if (theItem.entryType == entryCode)
{
UILog.Items.RemoveAt(i);
}
}
}
}
}
Any assistance would be greatly appreciated.
UPDATE: included UILogAddRow function
private void UILogAddRow(string entryCode, string entryIdentifier, string entryDetail)
{
bool itemExists = false;
int rowCount;
rowCount = UILog.Items.Count;
if (rowCount > 0)
{
for (int i = 0; i < rowCount; i++)
{
DataGridRow row = (DataGridRow)UILog.ItemContainerGenerator.ContainerFromIndex(i);
if (row != null)
{
UILogObject theItem = (UILogObject)row.DataContext;
if (theItem.entryType == entryCode)
{
itemExists = true;
}
}
}
}
else
{
//MessageBox.Show(rowCount.ToString());
}
if (itemExists != true)
{
UILog.Items.Add(new UILogObject() { entryType = entryCode, identifier = entryIdentifier, detail = entryDetail });
}
UILog.Items.Refresh();
}
instead of working with low-level container elements (DataGridRow), cast items to your known type, and then search and remove
private void UILogRemoveRow(string entryCode)
{
var item = UILog.Items.OfType<UILogObject>()
.FirstOrDefault(x => x.entryType == entryCode);
if (item != null)
UILog.Items.Remove(item);
}
I want realize arithmetic operations with my list, in this case:
Column "width" * Column "height" should re-Write the Column "Partial".
I have tried do a loop but It is not working.
I put a breakPoint at the row:
_Area[i].Partial = _Area[i].width * _Area[i].height;
And the debug never stop them I can think this line is not been readed.
This is my Collection View Model:
public class CollectionVM_Area : BindableBase
{
private Values_Area _Area = new Values_Area();
public Values_Area Area
{
get { return _Area; }
set { SetProperty(ref _Area, value); }
}
public CollectionVM_Area()
{
_Area.Add(new Area()
{
width=10,
height=11,
});
_Area.Add(new Area()
{
width=5,
height=5,
Partial=1,
});
bool NeedPartial = false;
int i = 0;
while (NeedPartial = false && i < _Area.Count)
{
if (_Area[i].Partida == true)
{
NeedPartial = true;
}
else
{
i++;
}
}
if (NeedPartial==true)
{
_Area[i].Partial = _Area[i].width * _Area[i].height;
NeedPartial = false;
}
else
{
NeedPartial = true;
}
}
}
My Project is a UWP but I think is no different in with a windows forms in lists, any help is appreciated.
You have two mistalkes in your code. First your while-loop makes an assignement instead of a comparisson (= towards ==). Thus the first term within your while-condition allways evaluates to false. Secondly your calculation is located outside the loop causing the NeedPartial-value to be set but not never be read which I doubt is what you want.
Write this therefor:
bool NeedPartial = false;
int i = 0;
while (NeedPartial == false && i < _Area.Count) // or even simpler: while (!NeedPartial ...)
{
if (_Area[i].Partida == true) // or simply: if (_Area[i].Partida) { ... }
{
NeedPartial = true;
}
else
{
i++;
}
if (NeedPartial==true) // if (NeedPartial) ...
{
_Area[i].Partial = _Area[i].width * _Area[i].height;
NeedPartial = false;
}
else
{
NeedPartial = true;
}
}
Edit: Answered.
The Correct Loop is:
bool NeedPartial = false;
int i = 0;
while (!NeedPartial && i < _Area.Count)
{
if (_Area[i].Partida)
{
NeedPartial = true;
}
else
{
i++;
}
if (NeedPartial)
{
_Area[i].Partial = _Area[i].width * _Area[i].height;
NeedPartial = false;
i++;
}
else
{
NeedPartial = true;
}
}
Thanks to HimBromBeere for your help.
hey guys m running into a problem, i have a forloop n in that i call a function, and in that function i have a if condition, i want to skip 1 loop if condition gets true, for this problm i was thinkin' to use goto statement but as i read in many forums that goto statement is an evil... can it be solved without using goto statement, ne ideas i dn't want to use 'goto'
for(int i=0;i<gridview.rows.count-1;i++)
{
//some operation;
aFunction(param1,param2);
}
public void aFunction(param1,param2)
{
//some operation;
if (!Regex.IsMatch(RechargeText, "successfully"))
{
RechargeStatus = "Failed";
Program.sp.SoundLocation =
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) +
"/aimlife_error.wav";
Program.sp.Play();
}
else if (Regex.IsMatch(RechargeText, "Processing") || Regex.IsMatch(RechargeText, "Not"))
{
// here i need to skip the Loop
}
else
{
Program.sp.SoundLocation =
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) +
"/aimlife_success.wav";
Program.sp.Play();
}
Program.StatusMessage = "Recharge Successful";
TextFill();
}
Actually there are some error list that are accepted errors, so i dn't need to update that in db, So my TextFill(); function shud not run for accepted errors
Snippet Edited
Simple, have the method return a bool. Then you can do:
for(int i=0;i<gridview.rows.count-1;i++)
{
//some operation;
if (aFunction(param1,param2)) break;
}
goto won't help you anyway. Basically you can't continue from a different method at all. The only simple way you can keep roughly your current flow is something like this:
bool shouldSkipNext = false;
for (int i = 0; i < gridview.Rows.Count - 1; i++)
{
if (shouldSkipNext)
{
shouldSkipNext = false;
continue;
}
// some operation
shouldSkipNext = aFunction(param1, param2);
}
public bool aFunction(param1,param2)
{
if (abc)
{
return true;
}
// Other stuff
return false;
}
Note that this will skip the entirety of the next iteration of the loop - which isn't the same as just continue. If you have more code after the call to aFunction and you want to skip that (which is the equivalent of continue) then it's simpler:
for (int i = 0; i < gridview.Rows.Count - 1; i++)
{
// some operation
if (aFunction(param1, param2))
{
continue;
}
// Other stuff which will sometimes be skipped
}
All you want to do is skip executing the TextFill() function when the condition if (Regex.IsMatch(RechargeText, "Processing") || Regex.IsMatch(RechargeText, "Not")) is true, thats all right?
You can simply return at that if condition, which will work out as you want:
else if (Regex.IsMatch(RechargeText, "Processing") || Regex.IsMatch(RechargeText, "Not"))
{
return;
} .... // rest of the code as it is
now when the above condition works out as true it will return to the for loop and go with the next iteration and so on...
Cheers
for(int i=0;i<gridview.rows.count-1;i++)
{
//some operation;
if (!aFunction(param1,param2)) continue;
}
public bool aFunction(param1,param2)
{
//some operation;
if (!Regex.IsMatch(RechargeText, "successfully"))
{
RechargeStatus = "Failed";
Program.sp.SoundLocation =
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) +
"/aimlife_error.wav";
Program.sp.Play();
}
else if (Regex.IsMatch(RechargeText, "Processing") || Regex.IsMatch(RechargeText, "Not"))
{
Program.StatusMessage = "Recharge Successful";
TextFill();
return false;
// here i need to skip the Loop
}
else
{
Program.sp.SoundLocation =
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) +
"/aimlife_success.wav";
Program.sp.Play();
}
Program.StatusMessage = "Recharge Successful";
TextFill();
return true;
}
If your code as posted is exactly how it is, then you could simply return, as the loop has no other operations.
No, it can not be solved with a goto... thankfully.
There is nothing that you can do inside the method that will change the control flow in the loop, you have to return something from the method and use that in the code of the loop:
for(int i = 0; i < gridview.rows.count - 1; i++) {
//some operation;
if (aFunction(param1,param2)) {
// do something more here
}
}
public bool aFunction(param1,param2) {
//some operation;
if(abc) {
//skip the current for-loop i.e i want to do "continue" here;
return false;
} else {
//normal
return true;
}
}
public static void main(String[] args) {
int param1 = 0, param2 = 0;
getResult(param1, param2);
}
public static void getResult(Object param1, Object param2) {
for (int i = 0; i < gridview.rows.count - 1; i++) {
if (!Regex.IsMatch(RechargeText, "successfully")) {
RechargeStatus = "Failed";
Program.sp.SoundLocation = System.IO.Path
.GetDirectoryName(System.Reflection.Assembly
.GetExecutingAssembly().Location)
+ "/aimlife_error.wav";
Program.sp.Play();
} else if (Regex.IsMatch(RechargeText, "Processing")
|| Regex.IsMatch(RechargeText, "Not")) {
// just skip here then
continue;
} else {
Program.sp.SoundLocation = System.IO.Path
.GetDirectoryName(System.Reflection.Assembly
.GetExecutingAssembly().Location)
+ "/aimlife_success.wav";
Program.sp.Play();
}
Program.StatusMessage = "Recharge Successful";
TextFill();
}
}
You should extract
Program.sp.SoundLocation = System.IO.Path
.GetDirectoryName(System.Reflection.Assembly
.GetExecutingAssembly().Location)
+ "/aimlife_success.wav";
Program.sp.Play();
and
RechargeStatus = "Failed";
Program.sp.SoundLocation = System.IO.Path
.GetDirectoryName(System.Reflection.Assembly
.GetExecutingAssembly().Location)
+ "/aimlife_error.wav";
Program.sp.Play();
into its own methods to make this code clearer, looks like a mess.
I have a piece of code where in I have an if block which when satisfied the flow goes into it and in there are nested if and else, if it does not satisfies any of the if block it should go into the else block but the problem i am facing is that it satisfies one if block and then goes into else as well. this is creating redundancy in my code.
it like this
if(condition = true)
{
if(condition1 == true)
{}
if(condition2 == true)
{}
else
{}
}
Now it satisfies condition 1 and then after performing if block operations goes into else also.
Please help. Code is in C#
You probably need something like this (notice else if with condition2):
if(condition)
{
if(condition1)
{}
else if(condition2)
{}
else
{}
}
You can skip '== true' in conditions.
get rid of the ==true's its just going to lead to a mistake like you made on the first line. also, add in else statements.
if (condition)
{
if (condition1)
{ }
else if (condition2)
{ }
else
{ }
}
As RaYell says, you need an extra "if" block. Here's a short but complete example to demonstrate:
using System;
public class Test
{
static void Main()
{
bool condition = true;
bool condition1 = true;
bool condition2 = false;
if (condition)
{
if (condition1)
{
Console.WriteLine("condition1");
}
// Note the "else if" here.
else if (condition2) {
Console.WriteLine("condition2");
}
else
{
Console.WriteLine("neither");
}
}
}
}
This prints "condition1" but not "neither".
If that isn't what you want, please clarify your question.
Put it like this
if(condition == true) {
if(condition1 == true) {}
else if(condition2 == true) {}
else {}
}
Ya you can use else if.Also you can write
if (condition==true) as if(condition) simply
For example
int i=2;
int j=3;
int k=4;
bool condition=k>1;
bool condition1=j<i;
bool condition2=j>i;
if (condition)
{
if (condition1)
{ }
else if (condition2)
{ }
else
{ }
}
Then, why don't you split up your code in methods, so you can do this:
if( condition)
{
if( condition1 )
{
DoSomethingForSituation1();
}
else
{
DoSomethingForSituation2();
}
}
else
{
DoSomethingForSituation1();
}
Also, when I look at it this way, you could say that 'condition' is redundant ?
Because either way, condition1 will always be true in some scenario ?
if( condition1 )
{
DoSomethingForSituation1();
}
else if( condition2 )
{
DoSomethingForSituation2();
}