What I have attempted to do is filter an ObservableCollection of Companies as the user is typing into a TextBox. The user is able to check CheckBoxes to add further criteria to what they would like to search on.
Sorry if this is a particularly long example but as I said, the method is very slow at the moment and I am looking for ways to improve it.
What I have tried:
The main issue with what I have tried so far is that it is really,really slow when the user types into the SearchBox. Here is how I apply the filter first of all;
CollectionViewSource.GetDefaultView(Companies).Filter = FilterCompanies;
When the user types into the TextBox this method is called;
private void SearchBoxCallApplyFilters(object sender, TextChangedEventArgs e)
{
CollectionViewSource.GetDefaultView(Companies).Refresh();
}
And then the FilterCompanies method;
private bool FilterCompanies(object obj)
{
var company = obj as CompanyModel;
if (searchBox.Text == string.Empty)
{
return true;
}
else if (CharactersOnly(company.Name.ToLower()).Contains((CharactersOnly(searchBox.Text).ToLower()))
|| CharactersOnly(company.Town.ToLower()).Contains((CharactersOnly(searchBox.Text).ToLower()))
|| CharactersOnly(company.Postcode.ToLower()).Contains((CharactersOnly(searchBox.Text).ToLower())))
{
if (FilterByCheckBoxes(company))
{
return true;
}
}
return false;
}
And finally the FilterByCheckBoxes method;
private bool FilterByCheckBoxes(CompanyModel company)
{
if (currentCheckBox.IsChecked == true && company.CurrentStatus == 1)
{
return true;
}
if (subbieCheckBox.IsChecked == true && company.Subcontractor == 1)
{
return true;
}
if (supplierCheckBox.IsChecked == true && company.Supplier == 1)
{
return true;
}
if (planthireCheckBox.IsChecked == true && company.Planthire == 1)
{
return true;
}
if (architectCheckBox.IsChecked == true && company.Architect == 1)
{
return true;
}
if (qsCheckBox.IsChecked == true && company.QS == 1)
{
return true;
}
if (projectManagerCheckBox.IsChecked == true && company.ProjectManager == 1)
{
return true;
}
if (structEngCheckBox.IsChecked == true && company.StructEng == 1)
{
return true;
}
if (servEngCheckBox.IsChecked == true && company.ServiceEng == 1)
{
return true;
}
return false;
}
CharactersOnly simply removes anything that isn't a Character from the TextBox Text;
private string CharactersOnly(string input)
{
char[] arr = input.ToCharArray();
arr = Array.FindAll(arr, (c => (char.IsLetterOrDigit(c))));
return new string(arr);
}