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

本文关键字:全局 数组 声明 何拆分 拆分 | 更新日期: 2023-09-27 18:37:22

我有一个由名字_姓氏组成的数组,所以它们会这样读Michael_JordanJavier_LopezGeorge_Jones

有一个循环设置来迭代其中的每一个,但我只想获取"之后的内容 我遇到的问题是数组是全局声明的,并且在很多地方都声明了它供我更改。 如果我尝试使用 .拆分函数我收到系统的错误.数组不包含拆分的定义。 在数组中获取"之后的数据的另一种选择是什么

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

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

我认为你的问题是"我想拆分数组 - 所以例如,它读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++;
}

您只能在字符串上使用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>。有了它,您可以继续工作。