How To Improve Filter Speed in ObservableCollection
I am using an ObservableCollection bound to a WPF DataGrid, the collection contains instances of a custom class (About 500) and the custom class is relativly basic (2 Strings, an IP and a custom enum)
I am using the following code to filter the grid (using all columns) as text is typed into a textbox.
private void searchBox_TextChanged(object sender, TextChangedEventArgs e)
{
CollectionViewSource SearchView = new CollectionViewSource();
SearchView.Filter += Search_Filter;
SearchView.Source = HostList;
dataGridMain.ItemsSource = SearchView.View;
}
void Search_Filter(object sender, FilterEventArgs e)
{
if (e.Item != null)
{
Host host = e.Item as Host;
try
{
bool foundInHost = false;
bool foundInIP = false;
bool foundInUser = false;
foundInHost = host.Hostname.ToLower().Contains(searchBox.Text.ToLower());
foundInIP = host.IP.ToString().Contains(searchBox.Text.ToLower());
foundInUser = host.Username.ToString().Contains(searchBox.Text.ToLower());
if (foundInHost || foundInIP || foundInUser)
{
e.Accepted = true;
}
else
{
e.Accepted = false;
}
}
catch (Exception ex)
{
}
}
}
It works but even on my shiny new i7 Laptop takes way too long.
Can anyone suggest a quicker method of filtering an observable collection?
Well all the ToLower and contains stuff isn't helping, but the most immediate fix would be
bool found = host.Hostname.ToLower().Contains(searchBox.Text.ToLower());
if (!found)
{
found = host.IP.ToString().Contains(searchBox.Text.ToLower());
if (!found)
{
found = host.Username.ToString().Contains(searchBox.Text.ToLower());
}
}
Don't need the other tests if one of them is already true.
searchBox.CharacterCasing to Lower would help as well.
And get rid of that exception swallow as well (the try catch). That's a really bad habit. At the very least add an errorlog to the app, log the exception and then swallow.
链接地址: http://www.djcxy.com/p/75234.html上一篇: 搜索数据网格wpf