Search code examples
c#stringlistsortingcollectionview

Filter a ICollectionView to order strings based off of how early a searched for term exists


I'm looking to arrange a ICollectionView called FilteredStrings of string objects based off of how early the searched string appears in each string. My ICollection is being instantiated with CollectionViewSource.GetDefaultView(_repository.GetObjects());.

The GetObjects() just returns a IEnumerable<string>() that were collected in the repository.

My original list looks like so:

ObjAect
ObjectA
AObject
ObjectB
ObjectC

The user would type in the searchbox in the UI, so in this case, they would search A and then the ICollectionView should filter to only show the strings that contain the search textm but then also reorder them based off of how early the searched test appears.

Results should be this:

AObject
ObjAect
ObjectA

My current code looks like this:

public void Search(string searchText)
{
    if (string.IsNullOrWhiteSpace(searchText))
    {
        FilteredComponentViewModels.Filter = null;
        return;
    }
    FilteredComponentViewModels.Filter = s => s.IndexOf(searchText, StringComparison.CurrentCultureIgnoreCase) >= 0;
}

Solution

  • For ICollectionView implementations which support sorting (identifiable by the CanSort property), we can assign an implementation of IComparer to the ICollectionView.CustomSort property.

    Since our underlying collection is simply IEnumerbale<string>, we can use an existing implementation of System.StringComparer from the System.Runtime.Extensions.dll assembly:

    FilteredComponentViewModels = GetDefaultView(_repository.GetObjects())
                                  as ListCollectionView;
    FilteredComponentViewModels.CustomSort = StringComparer.CurrentCultureIgnoreCase;