heyyoucoder
heyyoucoder

Reputation: 29

Split All The Listbox Elements And Add Them All To A New String Array

I have a problem about my code. I have a listbox and it has items (the number of items unknown). My listbox look like that:

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

And I want to transfer all my listbox items to a string array. After that, I want to split it (parameter=space) according to parameter. So the final look in the array:

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

It's my code:

         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.
         }

Thank you for answers.

Upvotes: 1

Views: 154

Answers (3)

Anu Viswan
Anu Viswan

Reputation: 18155

You can do the following

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

Upvotes: 2

MikeH
MikeH

Reputation: 4395

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[] { ' ' }); 

Upvotes: 2

Bizhan
Bizhan

Reputation: 17085

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


 var stringArray = results.ToArray();

Upvotes: 1

Related Questions