如何拆分声明为全局的数组

时间:2013-10-29 13:55:48

标签: c# arrays split

我有一个由名字_姓氏组成的数组,所以他们会这样读 迈克尔·乔丹 Javier_Lopez George_Jones

我有一个循环设置来遍历每一个,但我只想在" "之后采取什么?我遇到的问题是数组是全局声明的,并且它在很多地方被声明为我改变。如果我尝试使用.Split函数,我收到System.Array的错误,不包含split的定义。在" "之后获取数据的另一种选择是什么?在阵列?

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];
}

2 个答案:

答案 0 :(得分:0)

我认为你的问题是“我想拆分数组 - 所以例如它读取Javier_Lopez我想从数组中取出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++;
}

答案 1 :(得分: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>,其中包含您员工的所有姓氏。有了它,你可以继续工作。