0

I was trying to see if I could use the foreach statement to try and get the program I made to search through an entire array since I don't have a preset size for it and I don't want to play a guessing game for it. I tried this block of code but it tells me, "cannot implicitly convert type 'string' to 'int' and it points to the line 'if (query == search[k])

I'm not sure exactly what it is talking about but can someone please assist? Thank you.

    private void findLast_Click(object sender, EventArgs e)
    {
        query = textBox2.Text;
        search = File.ReadAllText(fileName).Split(new string[] { "\n", "\r\n", ":" }, StringSplitOptions.RemoveEmptyEntries);
        foreach (string k in search)
        {
            if (query == search[k])
            {
                MessageBox.Show("Match");
            }
            else
                MessageBox.Show("No Match");
        }
    }

4 Answers 4

3

in an each loop you have the object already.

private void findLast_Click(object sender, EventArgs e)
    {
        query = textBox2.Text;
        search = File.ReadAllText(fileName).Split(new string[] { "\n", "\r\n", ":" }, StringSplitOptions.RemoveEmptyEntries);
        foreach (string k in search)
        {
            if (query == k)
            {
                MessageBox.Show("Match");
            }
            else
                MessageBox.Show("No Match");
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

2

k is a string - therefore you can't use it as the index of an array. Try just query == k instead.

2 Comments

Wow, Worked. Thank you. I would of assumed that if I were to do it this way it would do it but to avoid further silly questions from me, what exactly is foreach and how do I use it? My understanding is that it is so you can go through the entire array or whatever you are looking at so you don't have to guess and input large numbers and such
Without wanting to be too harsh here, I think the best thing you could do would be to get a good introductory C# textbook - that should explain what foreach (and ever other keyword) does.
1

Change your test to

if (query == k)

the syntax that you are using is for simple for loop

for(int k; k < search.Length; k++)
{
   if (query == search[k])
       .....
} 

Comments

1

C# is not JavaScript... foreach gives you value of element, not an index:

 foreach (string currentItem in search)
 {
    if (query == currentItem)
    {...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.