将文本中的单词与列表框中的项目进行比较
Compare words in text with items in listbox
我正在 c#
中编写代码,它应该以每行单个单词的形式读取文本文件。例如:
"
aris
kronos
aris
kronos
aris
kronos
.
.
"
代码应该 读取 每 单行 一次,如果它们不存在,则将它们写在列表框中它。
所以步骤应该是:
1) read (the line in the file)
2) check ( if the words is already in the listbox )
3) If the word does not appear in the listbox creates a new item , if it does not skips to the next line.
我在这段代码中遇到的问题是,代码 比较 words 与 items 在列表框中 跳过 到下一个但是, 有时它不会 (看起来有时它确实跳过循环所以它没有)
string file = @"C:\file.txt";
int Readlines = 0;
int lineNumber = 1;
int AllLines = File.ReadLines(file).Count();
int m = 1;
for (int z = 1; z <= AllLines; z++)
{
string cLine = File.ReadLines(file).Skip(Readlines).Take(1).First();
foreach (string item in listBox1.Items)
{
while (item == cLine || cLine == "")
{
Match_Label.Text = "Found " + m + " matches!";
Readlines++;
cLine = File.ReadLines(file).Skip(Readlines).Take(1).First();
m++;
}
}
string newline = cLine;
listBox1.Items.Add(newline);
Readlines++;
}
var lines = File.ReadAllLines("file.txt").Distinct();
var result = lines.Union(listBox.Items.Cast<string>()).ToArray();
listBox.DataSource = result;
这里有一个不依赖于那些扩展方法的答案:
using (var reader = File.OpenText("c:\file.txt"))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (!listBox.Items.Contains(line))
listBox.Items.Add(line);
}
}
一旦您发现这有效,您就可以添加您的输出消息和计数器。您还可以包含其他条件,例如在包含之前确保该行的长度 > 0。
我正在 c#
中编写代码,它应该以每行单个单词的形式读取文本文件。例如:
"
aris
kronos
aris
kronos
aris
kronos . . "
代码应该 读取 每 单行 一次,如果它们不存在,则将它们写在列表框中它。
所以步骤应该是:
1) read (the line in the file)
2) check ( if the words is already in the listbox )
3) If the word does not appear in the listbox creates a new item , if it does not skips to the next line.
我在这段代码中遇到的问题是,代码 比较 words 与 items 在列表框中 跳过 到下一个但是, 有时它不会 (看起来有时它确实跳过循环所以它没有)
string file = @"C:\file.txt";
int Readlines = 0;
int lineNumber = 1;
int AllLines = File.ReadLines(file).Count();
int m = 1;
for (int z = 1; z <= AllLines; z++)
{
string cLine = File.ReadLines(file).Skip(Readlines).Take(1).First();
foreach (string item in listBox1.Items)
{
while (item == cLine || cLine == "")
{
Match_Label.Text = "Found " + m + " matches!";
Readlines++;
cLine = File.ReadLines(file).Skip(Readlines).Take(1).First();
m++;
}
}
string newline = cLine;
listBox1.Items.Add(newline);
Readlines++;
}
var lines = File.ReadAllLines("file.txt").Distinct();
var result = lines.Union(listBox.Items.Cast<string>()).ToArray();
listBox.DataSource = result;
这里有一个不依赖于那些扩展方法的答案:
using (var reader = File.OpenText("c:\file.txt"))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (!listBox.Items.Contains(line))
listBox.Items.Add(line);
}
}
一旦您发现这有效,您就可以添加您的输出消息和计数器。您还可以包含其他条件,例如在包含之前确保该行的长度 > 0。