Home > C#, WinRT > Using regular expressions to provide search suggestions in a Windows Store app

Using regular expressions to provide search suggestions in a Windows Store app

28/03/2013

Adding search suggestions to a Windows Store app is straightforward. We just need to handle the SuggestionRequest event of SearchPane object and provide the suggestions list.

Suppose we have a C#/XAML app in which we manage a list of content items, i.e. posts from a blog. In this case, it is a good practice to use the list of words contained in the items as search suggestions: we want to return the words in the repository that starts with the specified text.

We can easily accomplish this task using a regular expression that finds all matching words:

private void OnSuggestionsRequested(SearchPane sender,
                            SearchPaneSuggestionsRequestedEventArgs args)
{
    var results = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase);

    // Builds the regular expression.
    var query = string.Format(@"(?<!\w){0}(\w+|\s+)", args.QueryText.Trim());

    // Search among all the groups.
    var groups = SampleDataSource.GetGroups("AllGroups");
    foreach (var item in groups.SelectMany(g => g.Items))
    {
        var matches = Regex.Matches(item.Content, query, RegexOptions.IgnoreCase);

        foreach (Match match in matches)
            results.Add(match.Value.Trim());
    }

    // Orders the results and add them to the search suggestions.
    var suggestions = results.OrderBy(s => s).Take(5);
    args.Request.SearchSuggestionCollection.AppendQuerySuggestions(suggestions);
}

In this example, we use the SampleDataSource class that is included in the Grid App template, but the approach is the same regardless the actual data source.

We build a regular expression that extracts all the words starting with the specified string. Then, we find all the matches and add them to the results HashSet. Finally, we order the list and takes the first 5 elements, as this is the maximum number of items that can be shown as search suggestions.

Categories: C#, WinRT
  1. 07/06/2013 at 16:44

    Good web site you have got here.. It’s difficult to find good quality writing like yours nowadays. I really appreciate people like you! Take care!!

  1. 28/03/2013 at 12:48
Comments are closed.
%d bloggers like this: