[英]Returning string lines that only contain listbox items
I am trying to retrieve lines of data from a text file that contain items I added to a listbox, but it just keeps returning all lines of data from my test file: 我试图从包含我添加到列表框中的项目的文本文件中检索数据行,但它只是从我的测试文件中返回所有数据行:
foreach (var item in searchValList.Items)
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(searchValList.Text))
{
sb.AppendLine(line.ToString());
resultsTextBox.Text = sb.ToString();
}
else
{
resultsTextBox.Text = "The value was not found in this file";
}
}
}
You are searching for the same value in all the lines, (and virtually your outer loop is meaningless) 你在所有的行中搜索相同的值,(实际上你的外环是没有意义的)
Change following 改变以下
if (line.Contains(searchValList.Text))
to 至
if (item.Text != null && line.Contains(item.Text.ToString()))
I think it should be this way since you have a listbox. 我认为应该这样,因为你有一个列表框。 Try this : 尝试这个 :
foreach (var item in searchValList.Items)
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(item.ToString()))
{
sb.AppendLine(line.ToString());
resultsTextBox.Text = sb.ToString();
}
else
{
resultsTextBox.Text = "The value was not found in this file";
}
}
}
I see several problems in your code. 我在你的代码中看到了几个问题。
searchValList.Text
has to be item.ToString();
searchValList.Text
必须是item.ToString();
EOF
for fisrt iteration, in second Iteration it will always return null since EOF
already reached. 内部while循环旋转直到EOF
进行fisrt迭代,在第二次迭代中,它将始终返回null,因为EOF
已经到达。 It should be something like this. 它应该是这样的。
string[] lines = File.ReadAllLines("...");
var listboxItems = searchValList.Cast<object>().Select(x=> x.ToString()).ToList();
foreach (var line in lines)
{
if (listboxItems.Any(x=> line.Contains(x)))
{
sb.AppendLine(line);
}
}
if(sb.Length > 0)
{
resultsTextBox.Text = sb.ToString();
}
else
{
resultsTextBox.Text = "The value was not found in this file";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.