简体   繁体   中英

How I can realize parallel search in ObservableCollection?

I have an ObservableCollection, where Item has 2 properties(for example: Name and Id) and collection contains of 12k elements. So, i have a textbox, i want to search elements, which names contains my textbox value and add these elems in new collection.

in real-proj: Silverlight, TreeView(its ItemSource is my collection) which dynamically changing. And TreeView changing in UI.

My problem is just in slowly rendering results of search. I thing if it'll be parallel - it saves me.

for example, some code im using:

private ObservableCollection<ICDDocumentItemViewModel> LinearSearch(string searchText)
{
        var filteredCollection = new ObservableCollection<ICDDocumentItemViewModel>();
        if (searchText.Length > 3)
        {
            foreach (var itemViewModel in _linearCollection)
            {
                if (!itemViewModel.Model.Name.ToLower().Contains(searchText.ToLower())) continue;

                if (itemViewModel.Children.Count != 0)
                {
                    itemViewModel.IsExpanded = true;
                }

                filteredCollection.Add(itemViewModel);
            }
        }

    if(searchText.Length <= 3) 
    {
        return new ObservableCollection<ICDDocumentItemViewModel>(ICDItemsViewModelsMain);
    }
    return filteredCollection;
}

there is no need to have parallel processing in place normally, this code should help you here.

    private ObservableCollection<ICDDocumentItemViewModel> GetFiltered(string filter)
    {
        ObservableCollection<ICDDocumentItemViewModel> filteredCollection;

        if (filter.Length > 3)
        {
            filteredCollection = new ObservableCollection<ICDDocumentItemViewModel>(_linearCollection.Where(x => x.Name.ToLower().Contains(filter)));

            filteredCollection.ToList().ForEach(DetectChildren);
        }
        else
        {
            filteredCollection = new ObservableCollection<ICDDocumentItemViewModel>();
        }

        return filteredCollection;
    }

    private void DetectChildren(ICDDocumentItemViewModel item)
    {
        item.IsExpanded = item.Children.Any();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM