Skynet
Skynet

Reputation: 92

Using foreach statement

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");
        }
    }

Upvotes: 0

Views: 86

Answers (4)

Alexei Levenkov
Alexei Levenkov

Reputation: 100620

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

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

Upvotes: 1

Pow-Ian
Pow-Ian

Reputation: 3635

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");
        }
    }

Upvotes: 3

Steve
Steve

Reputation: 216363

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])
       .....
} 

Upvotes: 1

Philip Kendall
Philip Kendall

Reputation: 4314

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

Upvotes: 2

Related Questions