返回仅包含列表框项的字符串行

时间:2013-10-01 19:31:37

标签: c#

我正在尝试从包含我添加到列表框中的项目的文本文件中检索数据行,但它只是从我的测试文件中返回所有数据行:

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";
        }
    }
}

3 个答案:

答案 0 :(得分:2)

您正在所有行中搜索相同的值,(实际上您的外部循环毫无意义)

更改以下

 if (line.Contains(searchValList.Text))

 if (item.Text != null && line.Contains(item.Text.ToString()))

答案 1 :(得分:0)

我认为应该这样,因为你有一个列表框。试试这个:

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";
        }
    }
}

答案 2 :(得分:0)

我在你的代码中看到了几个问题。

  1. searchValList.Text必须为item.ToString();
  2. 内部while循环旋转到EOF进行fisrt迭代,在第二次迭代中,它将始终返回null,因为EOF已经到达。
  3. 在循环内的所有其他部分中,您正在设置“此文件中未找到该值” 这是完全错误的
  4. 它应该是这样的。

    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";
    }