listBox和拆分 [英] listBox and Split

查看:54
本文介绍了listBox和拆分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下所示的listBox

A,B,C
D,E,F,
D,F,C

我需要拆分这些字符串并删除重复项

我为此编写了以下代码

I have listBox like following

A,B,C
D,E,F,
D,F,C

i need to split those strings and remove duplications

i wrote following code for it

string[] array = new string[relatedWords.Items.Count];
          string[] words = null;

          for (int i = 0; i < relatedWords.Items.Count; i++)
          {

              object s = relatedWords.Items[i];
              array[i] = s.ToString();

              string synSet = array[i];
              words = synSet.Split('','');

          }



但它只需要最后一行DFC,但我需要三行中的所有字符串并删除重复项,请告诉我该怎么做?



but it will take only last line D F C but i need all strings in three lines and remove duplication pls tell me how to do it ??

推荐答案

如果我理解你正确的话,您想在ListBox的不同行上读入一个单词列表,并用``,''分隔,然后将它们编译成每个单词的单个列表,且没有重复?
在上面的示例中,列表为:
A
B
C
D
E
F
如果是这样,则:
1)不要使用数组-您不知道它需要多少个元素,因此请使用List< String>代替.
2)不要使用for循环-您不在乎您要花多少时间,因此请使用foreach循环.它使阅读变得更容易,并且更清楚地显示了您要执行的操作.
3)您需要第二个循环来处理从列表框获得的字符串中的每个单词.
这段代码将为您做到:
If I understand you right, you want to read in a list of words on separate lines of a ListBox, separated by '','', and compile them into a single list of each of the words, with no duplications?
In your example above, the list would be:
A
B
C
D
E
F
If so, then:
1) Don''t use an array - you don''t know how many elements it needs, so use a List<String> instead.
2) Don''t use a for loop - you don''t care how many time you go around, so use a foreach loop instead. It makes it easier to read, and more obvious what you are trying to do.
3) you need a second loop to handle each word in teh string you get from the ListBox.
This code will do it for you:
List<string> words = new List<string>();

foreach(object o in relatedWords.Items)
    {
    string s = o as string();
    if (s != null)
        {
        string[] separated = s.Split('','');
        foreach (string word in separated)
            {
            if (!string.IsNullOrEmpty(word))
                {
                if (!words.Contains(word))
                    {
                    words.Add(word);
                    }
                }
            }
        }
    }

您最终获得了单词中唯一词的列表,并且可以使用它们来完成所需的操作,包括在必须使用ToArray方法的情况下将其转换为数组.

You end up with the list of unique words in words, and can do what you need to with them, including converting it to an array if you must with the ToArray method.


这篇关于listBox和拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆