heymycoder
heymycoder

Reputation: 79

Split listbox items and split without selected item

To explain what I want to do the below is an example of what might be in my listbox (three list items of text):

                            listbox
                     ----------------------
                     |  hello my friends  |
                     |  how r u today?    |
                     |  i'm here          |
                     ----------------------

I want to split my listbox items (splitting where ever there is a space) into a 2 arrays. The first array will be my selected item (let's say we select "hello my friends", it's only a example; maybe second or third item can be selected) split and the second array will be my unselected items array. Like this;

string[] firstArray = {"hello", "my", "friends"}

string[] secondArray = {"how", "r", "u", "today?", "i'm", "here"}

But I don't know how can I do this... It's my code:

         string[] LBI = lb2.Items.OfType<string>().ToArray();                
         string[] selectedItemSplit=lb2.SelectedItem.ToString().Split(' '); 
         string jo = string.Join(" ", LBI);
         string[] sp = jo.Split(new char[] { ' ' });

Thank you for answers...

Upvotes: 0

Views: 992

Answers (2)

Jimi
Jimi

Reputation: 32248

  • Verify that there's at least one selected item, to avoid exceptions.
  • Insert in the first array the content of the currently selected ListBox item, splitting it using String.Split() (since we're splitting on a white space, no need to specify a separator: it's the default).
  • Take all the non-selected Items (.Where the Item index is not the current) and use SelectMany to flatten the arrays generated by splitting the content of each Item.

int currentIndex = listBox1.SelectedIndex;
if (currentIndex < 0) return;

string[] firstArray = listBox1.GetItemText(listBox1.Items[currentIndex]).Split();

string[] secondArray = listBox1.Items.OfType<string>().Where((item, idx) => idx != currentIndex)
                               .SelectMany(item => item.Split()).ToArray();

Upvotes: 0

Rufus L
Rufus L

Reputation: 37020

You can grab the selected item using lb2.SelectedItem and split it as you are doing, then take the rest of the items (filtering out the item with an index of lb2.SelectedIndex by using a Where clause) and then do a SelectMany on the results, splitting each on a space character:

var nonSelected = lb2.Items.OfType<string>()
    .Where((item, index) => index != lb2.SelectedIndex);

var first = lb2.SelectedItem.ToString().Split(' ');
var rest = nonSelected.SelectMany(others => others.Split(' ')).ToArray();

Upvotes: 2

Related Questions