2013-10-29 27 views
0

我有一個由名字組成的數組_姓,這樣他們就看,像這樣 Michael_Jordan Javier_Lopez George_Jones如何拆分即宣告全球

陣列我有一個循環建立通過每個迭代這些,但我只想採取「」後面的問題我所擁有的問題是,該數組是全局聲明的,並且它在很多地方被聲明爲我改變的地方。如果我嘗試使用.Split函數,則會收到System.Array的錯誤,其中不包含用於分割的定義。在陣列中的「」之後採用數據的另一種選擇是什麼?

public static string GetEmployees() 
{ 
    string queryString = "select employeeName from tbl_GlobalEmployeeData where state = 'AL'; 
    SqlConnection connection = new SqlConnection(Connection.MyConnectionString.ConnectionStrings[0]); 
    { 
     SqlCommand cmd = new SqlCommand(queryString, connection); 
     connection.Open(); 
     List<string> tempList = new List<string>(); 
     SqlDataReader reader = cmd.ExecuteReader(); 
     while (reader.Read()) 
     { 
      try 
      { 
       if (!reader.IsDBNull(0)) 
       { 
        tempList.Add(reader[0].ToString() + "_" + reader[1].ToString()); 
       } 
      } 
      catch 
      { 
       if (!reader.IsDBNull(0)) 
       { 
        tempList.Add(reader[0].ToString() + "_" + reader[1].ToString()); 
       } 
      } 
     } 
     reader.Close(); 
     AllCompanyEmployees.State.ThisStore = tempList.ToArray(); 
     for (int q = AllCompanyEmployees.State.ThisStore.GetLowerBound(0); q <= AllCompanyEmployees.State.ThisStore.GetUpperBound(0); q++) 
     { 
      return AllCompanyEmployees.State.ThisStore[q]; 
     } 
     return null; 
    } 
} 

}

for (int q = AllCompanyEmployees.State.ThisStore.GetLowerBound(0); q <= AllCompanyEmployees.State.ThisStore.GetUpperBound(0); q++) 
{ 
    //This line is where I get the error mentioned above 
    string lastName = AllCompanyEmployees.State.ThisStore.Split('_')[1]; 
} 
+3

我看不到您的問題和代碼之間的連接。你粘貼了錯誤的代碼片段嗎? – Baldrick

+1

''「'之後?什麼都沒有?你在說什麼?你的意思是分割下劃線嗎?請爲您的全局數組顯示代碼,並澄清您正在嘗試使用哪些示例。另外,你不能在數組上使用'Split'。這是'String'的一種方法。你需要在數組中的單個字符串上使用'Split'。 – tnw

+1

道歉到2試圖幫助,我沒有發佈錯誤的代碼片段。請查看我編輯中發佈的代碼。 – user2932408

回答

0

我覺得你的問題是「我要拆分的陣列 - 因此,例如,它讀取Javier_Lopez我想借此洛佩茲從數組」

非常簡單:

string last = yourString.Split(new char[] { '_' })[1]; 

同樣,你似乎在數組上使用它,這就是爲什麼你會得到這個錯誤。您需要遍歷數組,並對數組中的每個單獨的字符串執行此操作。

編輯:修改數組,只留下姓氏,試試這個:

int i = 0; 
foreach (string s in stringArray) 
{ 
    stringArray[i] = stringArray[i].Split(new char[] { '_' })[1]; 
    i++; 
} 
+0

如何對陣列中返回的每個名稱執行此操作?我遵循你所說的要做的事情,只是不去理解如何去做。 – user2932408

0

只能對字符串使用Split。所以,你可以做這樣的事情:

List<string> lastNames = new List<string>(); 
for (int q = AllCompanyEmployees.State.ThisStore.GetLowerBound(0); q <= AllCompanyEmployees.State.ThisStore.GetUpperBound(0); q++) 
{ 
    string lastName = AllCompanyEmployees.State.ThisStore[q].Split('_')[1]; 
    lastNames.Add(lastName); 
} 

在最後你將與你的員工的所有姓氏一個List<string>。有了這個,你可以繼續工作。