拆分所有列表框元素并将其全部添加到新的字符串数组

时间:2019-01-14 23:39:31

标签: c# arrays winforms split listbox

我的代码有问题。我有一个列表框,其中有项目(未知项目数)。我的列表框如下所示:

                       hello my friends
                       have a good day
                       how r u?
                       I will do it
                       aBcDe

我想将我所有的列表框项目都转移到字符串数组中。之后,我想根据参数将其拆分(参数=空格)。所以最后看一下数组:

{'hello','my','friends','have','a','good','day',how','r','u?','I','will ','do','it','aBcDe'}

这是我的代码:

         char[] sc={' '};
         string[] lb = mylistbox.Items.OfType<string>().ToArray();
         int cnt = lb.Length;
         for(int c=0; c<cnt; c++)
         {
            //I want to transfer the last array here.
         }

谢谢您的回答。

3 个答案:

答案 0 :(得分:2)

string[] lb = mylistbox.Items.OfType<string>().ToArray();

//Create a single string which contains all the items seperated by a space
string joined = string.Join(" ", lb); 

//Split the single string at each space
string[] split = joined.Split(new char[] { ' ' }); 

答案 1 :(得分:2)

您可以执行以下操作

var arrayOfItems = listBox.Items.OfType<string>().ToArray();
var result = arrayOfItems.SelectMany(s=>s.Split(' ')).ToArray();

答案 2 :(得分:1)

 List<string> results = new List<string>();
 for(int c=0; c<cnt; c++)
 {
    results.AddRange(lb[i].Split(' '));
 }


 var stringArray = results.ToArray();