c# - 找不到独特的词
问题描述
谁能告诉我我的代码有什么问题?基本上,在比较和之后,我只需words1
要从列表中添加唯一的单词。在语句中,如果我删除,那么它会找到匹配的单词(与我需要的相反)uniques
words1
words2
if
!
List<string> Unique(string lines1 ,string lines2, char[] separators)
{
string[] words1 = lines1.Split(separators, StringSplitOptions.RemoveEmptyEntries);
string[] words2 = lines2.Split(separators, StringSplitOptions.RemoveEmptyEntries);
List<string> uniques = new List<string>();
for (int i = 0; i < words1.Length; i++)
{
bool match;
for (int x = 0; x < words2.Length; x++)
{
if (!words1[i].Equals(words2[x]))
{
match = true;
uniques.Add(words1[i]);
break;
}
else
{
match = false;
}
}
}
return uniques;
}
解决方案
你可以对你的循环做一些小的改动
for (int i = 0; i < words1.Length; i++)
{
bool match=false;
for (int x = 0; x < words2.Length; x++)
{
if (words1[i].Equals(words2[x]))
{
match = true;
break;
}
}
if(!match && uniques.Contains(words1[i]))
{
uniques.Add(words1[i]);
}
{
uniques.Add(words1[i]);
}
}
为了使您的代码更短,您可以使用 LINQ
List<string> Unique(string lines1 ,string lines2, char[] separators)
{
string[] words1 = lines1.Split(separators, StringSplitOptions.RemoveEmptyEntries);
string[] words2 = lines2.Split(separators, StringSplitOptions.RemoveEmptyEntries);
return words1.Except(words2).ToList();
}
推荐阅读
- database - 如何在python中反向迭代mongo游标?
- php - 通过 URL 或 POST 的控制器参数
- java - 将 Observable 转换为 Single rx java
- javascript - Firefox 64 中断了一些日期解析
- docker - 为什么我发布的端口不起作用?
- javascript - 当我尝试运行此脚本时,它不起作用
- business-objects - 从对象/字符串中提取字符组
- mysql - 减少 Symfony 中 acl 类的 varchar 长度
- python-3.x - 10049:请求的地址在其上下文中无效.. Scrapy-Splash 未正确读取 URL
- android - 在改造放置请求中发送对象数组