C# string processing and condition - c#

I am reading and storing CMD commands in an array.
The last line in the array is the following string:
"[1] success"
I want to extract the 'success' part. So I stored the last element in a new variable and did some transformation:
var item = line[line.Count - 1];
item = item.Replace("[1]", "");
item = item.Replace("\"", "");
and then I do the following condition:
if (item == "success")
{
MessageBox.Show("Successful processing");
}
else
{
MessageBox.Show("There was an error.");
}
When I do MessageBox.Show(item); the exact characters I need are printed - success.
Nonetheless, the condition always returns the else output. I don't understand why?

Just check to see if item contains "success":
var item = line[line.Count - 1];
if (item.Contains("success"))
{
MessageBox.Show("Successful processing");
}
else
{
MessageBox.Show("There was an error.");
}

You can just use Contains like this:
if(line[line.Count - 1].Contains("success"))
{
MessageBox.Show("Successful processing");
}
else
{
MessageBox.Show("There was an error.");
}

You can simply use IndexOf:
if(line[line.Count - 1].IndexOf("success") > -1)
{
MessageBox.Show("Successful processing");
}
else
{
MessageBox.Show("There was an error.");
}

There is a space at the start of your variable value. Try calling Trim() first and then compare.
var item = line[line.Count - 1];
item = item.Replace("[1]", "");
item = item.Replace("\"", "");
item = item.Trim();

Related

compare the items in list in c#

i want to compare the selecteditem of combobox with the selecteditem of other combobox
for this i have registered all the comboboxes in a list and named it "panel1kilist"
now the problem i am facing is that when there are same items in two comboboxes first the messagebox shows "no mattch found" and then it shows "match found" actually it goes to the else statement of inner loop first and then to if statement kindly help
private void button1_Click(object sender, EventArgs e)
{
bool check = false;
bool check1 = false;[![in this image you can see that there are two same items but message is showing "no match found"][1]][1]
try[![after clicking on ok button of message box showing "no match found" this message box shows up][1]][1]
{
for (int i = 1; i < panel1kilist.Count; i++)
{
for (int j = i + 1; j < panel1kilist.Count; j++)
{
if (panel1kilist[i].SelectedItem.ToString() == panel1kilist[j].SelectedItem.ToString())
{
if (check == false)
{
MessageBox.Show("match found");
}
check = true;
}
else
{
if (check1 == false)
{
MessageBox.Show("no match found");
}
check1 = true;
}
}
}
}
catch (System.NullReferenceException)
{
MessageBox.Show("please fill all the boxes first");
}
}
Your question is not really clear but I still try to give you some help. As mentioned in the comments there are several small issues in your code:
1. The outter for-loop
for (int i = 1; i < panel1kilist.Count; i++)
You define i = 1, which means you skip the very first item in your panel1kilist because lists and arrays start at index 0
2. Use of your bool variables
if (panel1kilist[i].SelectedItem.ToString() == panel1kilist[j].SelectedItem.ToString())
{
if (check == false)
{
MessageBox.Show("match found");
}
check = true;
}
else
{
if (check1 == false)
{
MessageBox.Show("no match found");
}
check1 = true;
}
You define your bool variables before starting your for-loops. So whenever you set your variables check and check1 to true, the if conditions check == false and check1 == false will never return true anymore. So you will never get any message except the very first "Match found" and "no match found".
3. My proposed solution
Make use of the foreach-loop and break the loops once you found a match, after the loops just show the message. Code:
var matchFound = false;
foreach (var combobox in panel1kilist)
{
foreach (var comboboxToMatch in panel1kilist.Skip(1))
{
if (combobox.SelectedItem.ToString() == comboboxToMatch.SelectedItem.ToString())
{
matchFound = true;
// Stops the inner loop in case of a match
break;
}
}
// Stops the outer loop in case of a match
if(matchFound)
{
break;
}
}
if(matchFound)
{
MessageBox.Show("match found");
}

How can I retrieve my result everytime in Unity using C#?

This is my code
public void showMatch (string guess, string regx){
int outputCode;
MatchCollection mc = Regex.Matches (guess, regx);
foreach (Match m in mc) {
listOfTags [ctr] = m.Value;
ctr++;
}
checkOpeningTag = listOfTags [0];
checkClosingTag = listOfTags [1];
if (checkOpeningTag.Equals ("<h1>")) {
if (checkClosingTag.Equals ("</h1>")) {
outputCode = 3;
} else {
outputCode = 2;
}
} else {
outputCode = 1;
}
showError(outputCode);
}
public void showError(int checkError){
if (checkError == 1) {
error.text = "Sorry, no opening tag found.";
} else if(checkError == 2){
error.text = "Sorry, no closing tag found.";
}else if(checkError == 3){
error.text = "You got it right! Advancing to next level!";
}
}
If I try to input <'h1'> and <'h1'> (disregard ') , it will give me an error of
Sorry no opening tag
But when I try to correct it by submitting <'h1'> and <'/h1'> (disregard '), the error won't update. It still says Sorry no opening tag.
I tried using this code at the end of showMatch function
Debug.Log(outputCode);
I found that if the first input result is 2, the result everytime will always be 2. Same with if 1 is the result, the next results will be 1.
What am I doing wrong?

ListView.SelectedItems[0] Selection Error

Why is my program returning the following error?
Please be specific thanks.
PS: For whatever reason when there is only one item in the listview it works.
Error: InvalidArgument=Value of '1' is not valid for 'index'. Parameter name: index
Code:
if(e.Control == true)
{
try
{
string s = "";
string sCheck = "";
int select = 0;
int i = 0;
int position = 0;
if (i == 1)
{
i--;
}
if(select >= 1)
{
do
{
select--;
} while (select >= 1);
}
if (position >= 1)
{
do
{
position--;
} while (position >= 1);
}
foreach (object item1 in listView1.Items)
{
if (item1 == listView1.SelectedItems[select])
{
s = listView1.SelectedItems[select].Text;
sCheck = item1.ToString();
MessageBox.Show(item1.ToString());
}
else
{
select++;
}
}
string s1 = "";
foreach (object item in listView1.Items)
{
if (sCheck == item.ToString())
{
MessageBox.Show(item.ToString());
i++;
position++;
}
else
{
position++;
}
}
string s2 = listView1.Items.Count.ToString();
s1 = position.ToString();
if (i == 1)
{
string result = "Item: " + s + " || Position: " + s1 + " || Total Items: " + s2;
MessageBox.Show(result, "ListView Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show("Select a Item");
MessageBox.Show(ex.Message);
}
If there are no selected items the code will throw an exception at if (item1 == listView1.SelectedItems[select]) as there is no element at [0] in the collection.
Also, I believe the following code would have the same result as yours:
try
{
foreach (var item in listView1.SelectedItems)
{
MessageBox.Show(item.ToString());
}
if (listView1.SelectedItems.Count == 1)
{
var result = string.Format("Item: {0} || Position: {1} || Total Items: {2}",
listView1.SelectedItems[0], listView1.SelectedItems.Count, listView1.Items.Count);
MessageBox.Show(result, "ListView Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show("Select a Item");
MessageBox.Show(ex.Message);
}
The first three if statments are redundant as they occur directly after the variables are assigned (i.e, how could i equal 1 if you've just initialized it to 0?)
The two foreach loops show the same thing (show a message box with the selected items).
Position gets incremented for every selected item so it's always going to equal the total selected items.
If you provide more detail about what exactly you're trying to achieve I will try to help.

Looking for a specific info in a loop

string number = txtNumber.Text;
foreach (Account ac in tabAccounts)
{
if (txtNumber.Text == ac.Number)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + ac.Client;
break;
}
else
{
MessageBox.Show("Account Number not found");
}
}
Hello everyone, I'm fairly new here and with C# . So I have a class Account with client info which is stored in a text file.I want to loop through the array tabAccounts[200] and look if the entered user number corresponds to one that is in the text file. It works fine but when i enter let's say 222 it starts looping from the begging until it finds the number and if it doesn't it just keep looping and the message "Account Number not found" keeps coming out. When i remove the else statement it works fine but I want it that when a user enters a wrong number a message box will show...Hope you guys get it :( Tried googling but didnt find anything..
This can be done much more effective with LINQ:
var account = tabAccounts.SingleOrDefault(a => a.Number == txtNumber.Text);
if(account != null)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + account.Client;
}
else
{
MessageBox.Show("Account Number not found");
}
For your original code: The problem is that you are displaying the message inside the loop, every time the loop didn't find anything. This is a rewrite close to your original syntax, just to show you how to do it:
Account foundAccount = null;
foreach (Account ac in tabAccounts)
{
if (txtNumber.Text == ac.Number)
{
foundAccount = ac;
break;
}
}
if(foundAccount != null)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + foundAccount.Client;
}
else
{
MessageBox.Show("Account Number not found");
}
The minimum change required to achive your goal:
string number = txtNumber.Text;
bool found = false;
foreach (Account ac in tabAccounts)
{
if (txtNumber.Text == ac.Number)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + ac.Client;
found = true;
break;
}
}
if (!found)
MessageBox.Show("Account Number not found");
The problem is that you don't wait until you've finished searching to display "Account Number not found", you show it every time you find an Account that doesn't match. I'd rewrite it like this, using the FirstOrDefault extension method.
string number = txtNumber.Text;
Account ac = tabAccounts.FirstOrDefault(x => x.Number == txtNumber.Text);
if (ac != null)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + ac.Client;
}
else
{
MessageBox.Show("Account Number not found");
}
The best way to do this would be to set a flag when you find the element and then display outside of the loop
bool found = false;
string client;
string number = txtNumber.Text;
foreach (Account ac in tabAccounts)
{
if (txtNumber.Text == ac.Number)
{
found = true;
client = ac.Client;
break;
}
}
if (found)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + client;
}
else
{
MessageBox.Show("Account Number not found");
}

"else" completes even if "if" is true

I'm messing with some kind of dictionary, that is supposed to translate words from one textbox to other, and the other way around, but It doesn't act as I'd like it to. The code for the button is:
private void button1_Click(object sender, EventArgs e)
{
string[] lines = File.ReadAllLines("C:/words.txt");
int i = 0;
var items = from line in lines
where i++ != 0
let words = line.Split('|')
where words.Count() > 1
select new
{
word = words[0],
translation = words[1]
};
foreach (var item in items)
{
if (textBox1.Text == item.word)
{
textBox2.Text = item.translation;
}
if (textBox2.Text == item.translation)
{
textBox1.Text = item.word;
}
else
{
label3.Text = ("not found");
}
}
}
Edit: Doesn't work with "else if" either.
You need an else if, otherwise the else is only happening from the second if:
if (textBox1.Text == item.word)
{
textBox2.Text = item.translation;
}
else if (textBox2.Text == item.translation)
{
textBox1.Text = item.word;
}
else
{
label3.Text = ("not found");
}
Try to use else if (textBox2.Text == item.translation) instead of if (textBox2.Text == item.translation).
ELSE IF!
I find it best to avoid if statements where possible, and I especially try to avoid else and else if. The reason for this is that it simply gets confusing when there are multiple conditions to try and follow. Here is possibly a cleaner way to understand what is going on and also solve your issue.
foreach (var item in items)
{
if (textBox1.Text == item.word)
{
textBox2.Text = item.translation;
continue; // Don't process anything else in this loop.
}
if (textBox2.Text == item.translation)
{
textBox1.Text = item.word;
continue; // Don't process anything else in this loop.
}
label3.Text = ("not found");
}
Since we don't want any other logic to execute (my assumption) if one of our if statements is true, we simply use continue to skip the rest of the logic in the foreach and move to the next item.
Why is this in a loop anyway? Won't the text in the first iteration be overwritten by subsequent iterations?
From what I can see it is that there's no else if, that second if will only work if the first if is true. Try this:
foreach (var item in items)
{
if (textBox1.Text = item.word)
{
textBox2.Text = item.translation;
}
else if (textBox2.Text = item.translation)
{
textBox1.Text = item.word;
}
else
{
label3.Text = ("not found");
}
}

Categories