Reputation: 51
Can someone explain why the following code it isn't filtering?
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.
}
Upvotes: 0
Views: 38
Reputation: 628
The problem is with this:
if (lines.Contains(filter))
{
listAppts.Items.Add(lines);
}
The contains function returns true, if any of the lines matches, in its entirety, "Routine". What you really need is the list of lines where a substring of that line has "Routine". Eg.
List<string> res = lines.Where(x => x.Contains(filter)).ToList();
listAppts.Items.Addrange(res);
Upvotes: 2
Reputation: 470
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();
}
Upvotes: 1