c# - 从 TXT 文件中读取所有行并仅在每行 C# 的每个第一个字符串中搜索

标签 c#

我在 listView 中显示搜索结果时遇到问题。我有一个 TXT 文件,我只想搜索文件每一行的第一个单词。我不知道应该在什么条件下执行此操作...我正在阅读有关 FirstORDefault 选项的信息,但没有使用我的 if 语句。下面是我的文本文件和显示 View 表单。

希望收到您的来信....谢谢。请帮忙。

    private void btnSH_Click(object sender, EventArgs e)
    {
        FileStream history = File.Open("C:\\Users\\Sofia\\TestFolder2\\logfile.txt", FileMode.Open, FileAccess.Read);
        StreamReader hRead = new StreamReader(history);
        String viewHistory = hRead.ReadToEnd();
        String[] hArray = viewHistory.Split('\n');

        hRead.Close();
        history.Close();

        if (txtBoxSH2.Text != "")
        {
            string searchString = txtBoxSH2.Text;
            historyLstBox.Items.Clear();

            foreach (string line in hArray)
            {
                if (line.ToUpper().IndexOf(searchString.ToUpper())!= -1)
                {
                    historyLstBox.Items.Add(line);
                }
            }

        }
    }

最佳答案

您可以使用 LINQ 来提供更简洁的代码:

private IEnumerable<string> GetMatchingLines(string filename, string word)
{
    return File.ReadLines(filename)
               .Where(line => string.Equals(line.Split(' ').FirstOrDefault(), 
                                            word,
                                            StringComparison.InvariantCultureIgnoreCase));
}

然后只需将此方法的结果添加到 historyLstBox.Items

关于c# - 从 TXT 文件中读取所有行并仅在每行 C# 的每个第一个字符串中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27101625/

相关文章:

c# - List.Any 得到匹配的字符串

c# - Azure Functions 无法从 ABCpdf Nuget 包加载 DLL

c# - 应用程序卡在全屏?

c# - 使用 text={binding var} 属性验证在文本框控件中输入的值

c# - 在不验证签名的情况下确定pdf文件是否在c#中具有数字签名

C# - 作为执行异步任务的委托(delegate),我仍然需要 System.Threading 吗?

c# - 当存在上下文切换时,获取锁的开销是否取决于操作系统计时器分辨率?

c# - 强制重新下载 nuget 包

c# - 计算 CRC16 (Modbus) 值的函数

c# - using 子句会关闭此流吗?