2010-11-30 128 views
1

我有这样的代码string.compare和字符串比较

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

但这里使用(串),使问题的情况下,sensitiveness.So我要到位(串)的使用string.comapare。

任何人都可以给我任何提示如何使用它。

回答

1

试试这个:

if (string.Compare((string) cmbOperations.SelectedItem, 
     "NonForeignKeyTables", true) == 0) // 0 result means same 
    GetNonForeignKeyTables(); 
0

MSDN有关于string.compare方法真的很好的解释.. 你只需要编写

String.Compare (String, String) 

来比较你的字符串..用开关指令的情况下使用这将是确定..

使用

String.Compare (String, String, boolean) 

要设置的情况下comparaison

+0

查看我的答案,为什么我不会使用`Compare`。另外还不清楚switch/case如何与此相关。 – 2010-11-30 07:58:07

0

对于区分大小写的比较:

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

    if(string.Compare(a, b, true) == 0) { 
     Console.WriteLine("Equal"); 
    } 
5

我建议你使用:

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

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

选择正确的字符串比较可能会非常棘手。有关更多信息,请参阅此MSDN article

使用Compare其他人建议,只是因为这是不正确的重点将不会建议 - Compare被设计用于何种顺序字符串应该出现时,他们分类测试。这有副产品允许你测试平等,但这不是主要目标。使用Equals表明你所关心的只是平等 - 如果两个字符串不相等,你不关心哪一个会先来。使用Compare工作,但它不会让您的代码尽可能清楚地表达自己。