naz naz
naz naz

Reputation: 11

How can I compare the variables in my array with the variable entered in the textbox in c#?

I created an array of mysql data. I want to compare each element of my array with the value entered in the textbox and print the result, but it doesn't work the way I want.Any idea of doing so?

**edit My goal is to actually make a guessing game, so I created two arrays with Mysql data called answers and questions. And what I want to do is take the value from the user and if it is true, for example my first answer 'fashion' matches the guess the user entered in the textbox, I want the label to write correct and continue with the next answer and try to find the next answer. **

        private void button1_Click(object sender, EventArgs e)

    {
        List<string> cevaplar = new List<string>();
        List<string> sorular = new List<string>();
        

        MySqlCommand command = new MySqlCommand("Select cevap,soru From soru_cevap", con.cn);

        con.cn.Open();

        MySqlDataReader oku = command.ExecuteReader();
        while (oku.Read())
        {

            var cevap = oku.GetString(0);
            var soru = oku.GetString(1);

            cevaplar.Add(cevap);
            sorular.Add(soru);

        }

        con.cn.Close();

        for(int i=0;i<cevaplar.Count;i++)
        {
            string tahmin = textBox1.Text;
            if (cevaplar.Any(item => item == tahmin))
            {
                label1.Text= "true";
                continue;

            }
            else
            {
                label1.Text = "false";
                break;
            }
        }


    }

Upvotes: 0

Views: 119

Answers (1)

Just Shadow
Just Shadow

Reputation: 11881

You can achieve your result by using the LINQ method Any() or Contains() (which will handle the looping for you) like this:

string tahmin = textBox1.Text;
// label1.Text = cevaplar.Any(item => item == tahmin) ? "true" : "false"
label1.Text = cevaplar.Contains(tahmin) ? "true" : "false"

Notes:

  • Don't forget to add using System.Linq to the top of your file if you use Any().
  • If you want the check to be case-insensitive you can use Any with item.Equals(tahmin, StringComparison.OrdinalIgnoreCase) instead of item == tahmin
  • The faster solution will still be Contains. But it doesn't allow lambdas, so the point above will not work there.
  • Any vs Contains discussion can found here

Upvotes: 4

Related Questions