C# 无法从列表框中删除停止字项目
您好,我是c#新手,希望从列表框中删除所有包含停止词的字符串。我的代码是:C# 无法从列表框中删除停止字项目,c#,listbox,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].ToStri
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的#有人能帮我吗?您在从列表中删除项目时多次访问
项目[]
,因为您有多个if语句
因此,如果两条语句为真,则您将尝试删除同一索引两次
要么将代码更改为else if(s),要么重新编写代码,因为简单地将所有停止词放入列表并过滤项
集合是一个混乱的代码
这可以如何工作的示例:
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));
或者重构代码,将停止词放入列表中
List<string> stopWords = new List<string>()
{
"the",
"an"
};
List stopWords=新列表()
{
",,
“安”
};
然后在listview项上迭代:
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);
}
}
for(int i=0;istopWords.Contains(word)))
{
词汇。项目。删除(i);
}
}
.Any
是数组的linq扩展,如果任何数组项与条件匹配,它将返回true…我不明白这一点solution@user3154778因为我真的是一个好人,我给你举了更多的例子。。。希望这将最终帮助您;)在我的情况下,以及在你的情况下,有一个类似的错误,停止字一个事故,我们的两个代码没有做任何事情,这停止word@user3154778,在你的评论中,你说“事故”不起作用。你的意思是把大写字母“A”放进去吗?在这种情况下,您可以调用glossarywords.Items[n].ToString().ToLower().Contains(“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);
}
}