简体   繁体   中英

C# Username comparison (2 strings)

Okey, so i think i'm missing something completely obvious here. I just need a fresh pair of eyes to look at it, i'm tired.

I'm literally just comparing 2 string in an if statement but it doesn't think its the same.

public Boolean checkusn(String username)
    {
        MySqlDataReader reader = sendcmd("SELECT username FROM `users`");
        Boolean taken = true;
        while (reader.Read())
        {
            for (int i = 0; i < reader.FieldCount; i++)
            {
                Console.Write(reader.GetString(i) + " " + username + " ");
                if (username == reader.GetString(i))
                {
                    taken = false;
                    label17.Text = "Username already taken";
                }
                else
                {
                   taken = true;
                   label17.Text = "Username not taken";
                }

            }
        }
        return taken;
    }

The output is this:

hayhay hayhay test hayhay 

so its comparing hayhay with hayhay and hayhay with test. But it doesn't think them as the same....

You shoud leave the loops when taken == true. Right now you're always returning the bool value only for the last element in the table.

I have simplified your method addressing the concerns and hopefully making it easier to maintain and understand. Changes include:

  • Correct logic errors (break out of loop when found)
  • Ensure passed in parameter is actually validated in some way (at least now leading / trailing spaces are removed)
  • Explicitly do a case insensitive comparison (You could use string.compare if you prefer)
  • Code reduction

     public bool checkusn(String username) { MySqlDataReader reader = sendcmd("SELECT username FROM `users`"); int foundCount = 0; string usernamePassedIn = username.Trim().ToUpper(); while (reader.Read() && foundCount == 0) { for (int i = 0; i < reader.FieldCount; i++) { string usernameReadFromDb = reader.GetString(i).Trim().ToUpper(); if (usernamePassedIn == usernameReadFromDb) foundCount++; if (foundCount > 0) break; } } label17.Text = foundCount > 1 ? "Username already taken" : "Username not taken"; return foundCount > 0; } 

You could further improve things by returning the usernames UPPER CASED and TRIMMED from the database directly. Also note that you don't take into account the case where your parameter username may be NULL or empty.

By counting the number of times you find a match you could do other things as needed. So instead of breaking out immediately of your loops for example.

I am no expert on the MySQL reader you are using there, but as you are returning a single field it does appear a little odd that you are doing a FOR loop over the fields - I am guessing you could actually do away with your FOR loop entirely viz:

    public bool checkusn(String username)
    {
        MySqlDataReader reader = sendcmd("SELECT username FROM `users`");
        int foundCount = 0;
        string usernamePassedIn = username.Trim().ToUpper();

        while (reader.Read() && foundCount == 0)
        {
                string usernameReadFromDb = reader.GetString(0).Trim().ToUpper();
                if (usernamePassedIn == usernameReadFromDb)
                    foundCount++;
            }

        label17.Text = foundCount > 1 ? "Username already taken" : "Username not taken";
        return foundCount > 0;
    }

Don't use ==

From this MSDN article

When you compare strings, you should use the methods that explicitly specify what kind of comparison you intend to perform. This makes your code much more maintainable and readable. Whenever possible, use the overloads of the methods of the System.String and System.Array classes that take a StringComparison enumeration parameter, so that you can specify which type of comparison to perform. It is best to avoid using the == and != operators when you compare strings. Also, avoid using the String.CompareTo instance methods because none of the overloads takes a StringComparison.

Thanks for the tips guys, i dont use c# often. Although what you mentioned was not the case, it helped me find my mistake.

I was stupidly not stopping the for loop once it found the username, so as it was going over to the next username in the list it was setting it back to true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM