在文本文件中搜索一行并显示结果
问题描述:
我想为我的迷你项目制作一个搜索框,它应该工作的方式是您键入某个名称,然后在文本文件中搜索该单词,如果没有找到结果,则显示No results
。在文本文件中搜索一行并显示结果
文本文件包括:
例1 0
例2 1
例2 2
范例4 3
例5 4
我希望能够搜索名称并显示找到的名称和年龄。
在文本框中,当按钮被点击:Example5
< ---(我正在寻找)
一些伪代码:
private void DynamicButton_Click(object sender, EventArgs e)
{
Text = this.dynamicTextBox.Text;
// This is how I want it to work:
// search names.txt for Text
// Get the entire line it was found on
if (found) {
MessageBox.Show(result);
}
else
{
MessageBox.Show("No results");
}
}
最终结果:该说Example5 4
答
尝试这样:
private void DynamicButton_Click(object sender, EventArgs e)
{
// Assign text local variable
var searchText = this.dynamicTextBox.Text;
// Load lines of text file
var lines = File.ReadAllLines("names.txt");
string result = null;
foreach(var line in lines) {
// Check if the line contains our search text, note this will find the first match not necessarily the best match
if(line.Contains(searchText)) {
// Result found, assign result and break out of loop
result = line;
break;
}
}
// Display the result, you could do more such as splitting it to get the age and name separately
MessageBox.Show(result ?? "No results");
}
注意,对于这个答案工作,你将需要进口System.IO
+0
非常感谢! – Roto
答
您可以使用File.ReadLines
:
private void dynamicButton_Click(object sender, EventArgs e)
{
string path = "../../text.txt";
var lines = File.ReadLines(path).ToArray();
var found = false;
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].Contains(dynamicTextBox.Text))
{
label1.Text = i + 1 + "";
found = true;
}
}
if (!found)
label1.Text = "Not Found";
}
答
做这样的:
string[] lines = File.ReadAllLines("E:\\SAMPLE_FILE\\sample.txt");
int ctr = 0;
foreach (var line in lines)
{
string text = line.ToString();
if (text.ToUpper().Contains(textBox1.Text.ToUpper().Trim()) || text.ToUpper() == textBox1.Text.ToUpper().Trim())
{
//MessageBox.Show("Contains found!");
ctr += 1;
}
}
if (ctr < 1)
{
MessageBox.Show("Record not found.");
}
else
{
MessageBox.Show("Record found!");
}
或者您可以使用此Expression
最小化您的代码:
string[] lines = File.ReadAllLines("E:\\SAMPLE_FILE\\sample.txt");
var tolist = lines.Where(x => (x.ToUpper().Trim() == textBox1.Text.ToUpper().Trim())).FirstOrDefault();
if (tolist != null)
{
MessageBox.Show("Record found.");
}
else
{
MessageBox.Show("Record not found.");
}
如果您需要帮助的代码,您需要发布您的代码。这不是一个代码写入服务。请阅读[问]并参加[旅游] – Plutonix