【问题标题】:Split listbox items and split without selected item拆分列表框项目并拆分没有选定项目
【发布时间】:2019-06-12 04:14:07
【问题描述】:

为了解释我想要做的事情,下面是我的listbox 中的一个示例(三个文本列表项):

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

我想将我的 listbox 项目(在有空间的地方拆分)分成 2 个数组。第一个数组将是我选择的项目(假设我们选择“你好我的朋友”,这只是一个示例;也许可以选择第二个或第三个项目)拆分,第二个数组将是我未选择的项目数组。像这样;

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

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

但我不知道我该怎么做... 这是我的代码:

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

感谢您的回答...

【问题讨论】:

    标签: c# arrays winforms split listbox


    【解决方案1】:

    您可以使用lb2.SelectedItem 抓取所选项目并按照您的方式拆分它,然后取出其余项目(使用Where 子句过滤掉索引为lb2.SelectedIndex 的项目)然后对结果执行SelectMany,将每个结果拆分为空格字符:

    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();
    

    【讨论】:

    • 但我不会每次都选择第一项进行拆分。也许第二个项目会被选中,也许三个。它适用于所有情况吗?
    • 哦,对不起,我误会了!我会更新答案。
    • 好的,修改为只抓取未选中的项目。
    【解决方案2】:
    • 验证至少有一个选定的项目,以避免异常。
    • 在第一个数组中插入当前选中的 ListBox 项的内容,使用String.Split() 分割它(因为我们是在空白处分割,所以无需指定分隔符:这是默认设置)。
    • 取所有未选中的Item(.WhereItem索引不是当前的),使用SelectMany将每个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();
    

    【讨论】:

    • 我记得你,吉米。你的答案总是有效的。谢谢。
    猜你喜欢
    • 2012-09-30
    • 2012-02-26
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多