无法从ListBox中删除停止Word项目

时间:2014-01-03 17:51:41

标签: c# listbox

您好,我是c#的新手,想要从列表框中删除包含停用词的所有字符串。我的代码是:

for (int n = glossarywords.Items.Count - 1; n >= 0; --n)
{
    if (glossarywords.Items[n].ToString().Contains("the "))
    {
        glossarywords.Items.RemoveAt(n);
    }
    if (glossarywords.Items[n].ToString().Contains("an"))
    {
        glossarywords.Items.RemoveAt(n);
    }
    if (glossarywords.Items[n].ToString().Contains(" the"))
    {
        glossarywords.Items.RemoveAt(n);
    }
}

glossarywords是列表框,我想从中删除那些包含停止词的字符串,如is,am,are等。 我在列表框中的示例数据是:

     an accident
     accident injury
     an accident
     accident cause
     accident is
     is accident

在我的代码旁边,如果不会出现重复的单词,它可以正常工作,但如果发生像事故这样的重复单词则不起作用!所以我是c#的新手可以请任何人帮助我吗?

1 个答案:

答案 0 :(得分:3)

您正在从列表Items[<index>]中删除项目时多次访问glossarywords,因为您有多个if语句...

因此,如果两个陈述为真,那么您试图两次删除相同的索引......

要么将代码更改为else,要么将其重新编写,因为将所有停用词放入列表并过滤Items集合是一个混乱的代码。

这可行的示例:

var keywords = new List<string>() { "Hello", "world" };

var list = new List<string>() { "Hello", "this", "is", "the", "world" };

var removed = list.RemoveAll(p => keywords.Contains(p));

编辑:

好的,再次使用else if语句,例如:

for (int n = glossarywords.Items.Count - 1; n >= 0; --n)
{

    if (glossarywords.Items[n].ToString().Contains("the "))
    {
        glossarywords.Items.RemoveAt(n);
    }
    else if (glossarywords.Items[n].ToString().Contains("an"))
    {
        glossarywords.Items.RemoveAt(n);
    }
    else if (glossarywords.Items[n].ToString().Contains(" the"))
    {
        glossarywords.Items.RemoveAt(n);
    }
}

或重构您的代码,将您的停用词放入列表

List<string> stopWords = new List<string>()
{
    "the",
    "an"
};

然后对列表视图项进行迭代:

for (int i = 0; i < glossarywords.Items.Count; i++)
{
    // get the item as string
    string itemValue = glossarywords.Items[i].ToString();

    // split the string by empty space which will separate all words
    string[] itemWords = itemValue.ToString().Split(' ');

    // check if any of the words within the current value is within the stopwords list
    if (itemWords.Any(word => stopWords.Contains(word)))
    {
        glossarywords.Items.RemoveAt(i);
    }
}

.Any是数组的linq扩展,如果任何数组项与条件匹配,则返回true ...