string.compare и строка для сравнения - PullRequest
1 голос
/ 30 ноября 2010

У меня есть такой код

private void btnStartAnalysis_Click(object sender, EventArgs e)

            {

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "PrimaryKeyTables")
            {
            //This is the function call for the primary key checking in DB
            GetPrimaryKeyTable();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "NonPrimaryKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetNonPrimaryKeyTables();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "ForeignKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetForeignKeyTables();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "NonForeignKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetNonForeignKeyTables();
            }

        if((string) (cmbOperations.SelectedItem) == "UPPERCASEDTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetTablesWithUpperCaseName();
            }

        if((string) (cmbOperations.SelectedItem) == "lowercasedtables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetTablesWithLowerCaseName();
            }
        }

Но здесь использование (string) создает проблему в случае чувствительности к регистру. Поэтому я хочу использовать string.comapare вместо (string).

Может ли кто-нибудь дать мне подсказку, как его использовать?

Ответы [ 4 ]

5 голосов
/ 30 ноября 2010

Я предлагаю вам использовать:

// There's no point in casting it in every if statement
string selectedItem = (string) cmbOperations.SelectedItem;

if (selectedItem.Equals("NonPrimaryKeyTables",
                        StringComparison.CurrentCultureIgnoreCase))
{
    ...
}

Выбор правильного сравнения строк может быть сложным. См. Эту статью MSDN для получения дополнительной информации.

Я не предложил бы использовать Compare, как предлагали другие, просто потому, что это неправильный акцент - Compare предназначен для проверки того, в каких строках порядка должны появляться отсортированы. Это побочный продукт, позволяющий вам проверять равенство, но это не главная цель. Использование Equals показывает, что все, что вас волнует, это равенство - если две строки не равны, вам все равно, что будет первым. Использование Compare будет работать , но это не заставит ваш код выражать себя настолько ясно, насколько это возможно.

1 голос
/ 30 ноября 2010

попробуйте это:

if (string.Compare((string) cmbOperations.SelectedItem, 
        "NonForeignKeyTables", true) == 0) // 0 result means same
    GetNonForeignKeyTables();
0 голосов
/ 30 ноября 2010

Для сравнения без учета регистра:

    string a = "text1";
    string b = "TeXt1";

    if(string.Compare( a, b, true ) == 0) {
        Console.WriteLine("Equal");
    }
0 голосов
/ 30 ноября 2010

MSDN действительно хорошее объяснение метода string.compare. тебе просто нужно написать

String.Compare (String, String) 

для сравнения ваших строк .. при использовании инструкции Switch-case все будет хорошо ..

Использование

String.Compare (String, String, boolean)

Чтобы установить сравнение случаев

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...