通过文本文件中的内容过滤列表框

时间:2019-02-20 20:32:28

标签: c#

有人可以解释为什么下面的代码没有被过滤吗?

private void LoadAppointments()
{
    // load all "Routine" appointments into the listbox
    string[] lines = File.ReadAllLines(@"D:\appointments.txt");

    string filter = "Routine";

    // this part is not working. It isn't filtering by only showing 
    // "Routine" appointments in the listbox.
    if (lines.Contains(filter))
    {
        listAppts.Items.Add(lines);
    }

    listAppts.Items.AddRange(lines);  
    // if I leave this out, nothing gets loaded, but if I add this 
    // line, everything gets loaded without being filtered.
}

2 个答案:

答案 0 :(得分:2)

问题出在这里:

if (lines.Contains(filter))
{
    listAppts.Items.Add(lines);
}

如果任何行全部匹配为“例程”,则contains函数将返回true。您真正需要的是该行的子字符串具有“例程”的行列表​​。例如

List<string> res = lines.Where(x => x.Contains(filter)).ToList();
listAppts.Items.Addrange(res);

答案 1 :(得分:1)

    private void LoadAppointments()
{
    // load all "Routine" appointments into the listbox
    string[] lines = File.ReadAllLines(@"D:\appointments.txt");

    string filter = "Routine";

    var filteredLines = lines.Where(line => line.Contains(filter)).ToList();
}