简体   繁体   English

将一维数组拆分为2个数组

[英]Split single dimension array into 2 arrays

Sorry for not being so clear in advance, it is kinda hard for me to describe. 对不起,因为事先没有这么清楚,我很难形容。 Right now I am having a bit of an issue with data management. 现在,我在数据管理方面遇到了一些问题。 I have thing string inside a database for graphic data. 我在图形数据数据库中有东西字符串。

f0||Title Text||f1||Subtitle Text||f2||Option 1||f3||Option 2

Right now, I can query the data and split the string shown above into a single dimensional array by using this "||" 现在,我可以使用“ ||”查询数据并将上面显示的字符串拆分为一维数组。 separator. 分隔器。 As of right now the code is as follows. 到目前为止,代码如下。

MySQLHandler handler = new MySQLHandler(this.text_DataIP.Text.ToString());
        List<string>[] data = handler.SelectCG("graphics", text_CGBuffer.Text.ToString());
        string x = data[2][0].ToString();
        string[] y = x.Split(new string[] { "||" }, StringSplitOptions.None);
        // For each string in the new string array, lets separate them into their own strings for adding to the DataSet
        for (int n = 0; n < y.Length; )

        DataSet dataset = new DataSet();
        DataTable table = dataset.Tables.Add();
        table.Columns.Add("fieldid");
        table.Columns.Add("values");

What is missing is the code that for every other string in the array, it will alternate in adding the data to the DataTable. 缺少的代码是数组中的每个其他字符串都会交替添加数据到DataTable中。 For example, "f0, f1, f2, f3" will go into the column "fieldid" and the other strings will go into the values column. 例如,“ f0,f1,f2,f3”将进入“ fieldid”列,其他字符串将进入“值”列。

I was thinking about doing a for loop but I do not know if that is the most efficient way of doing it. 我当时正在考虑做一个for循环,但是我不知道这是否是最有效的方法。 What would be more efficient and how would I achieve this? 有什么会更有效,我将如何实现呢?

Here is an example that I tested with. 这是我测试过的一个例子。 I think it will work for you: 我认为它将为您工作:

string x = "f0||Title Text||f1||Subtitle Text||f2||Option 1||f3||Option 2";
string[] y = x.Split(new string[] { "||" }, StringSplitOptions.None);

DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add();
List<object> rowvalues = new List<object>(); //to hold the row values

//Loop through 2 at a time,  
for (int n = 0; n < y.Length; n = n + 2) 
{
    dt.Columns.Add(y[n]); //add the column
    rowvalues.Add(y[n + 1]); //and save the value
}

//Create the row
var dr = dt.NewRow();
//Set the row values
dr.ItemArray = rowvalues.ToArray();

A for loop would suffice. for循环就足够了。 The most efficient way is to iterate the loop only once to separate the id and value. 最有效的方法是仅循环一次以分离ID和值。

        for (int i = 0; i < y.Length; i++)
        {
           string fieldid = y[i];
            string value = y[++i];
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM