Home > Software engineering >  Xamarin: ListView search whether Uppercase or Lowercase
Xamarin: ListView search whether Uppercase or Lowercase

Time:04-30

I'm creating a Search Bar and can't seem to get results back. It seems to be case sensitive. Is there any way I can make it case insensitive so the user can search in Lowercase or Uppercase and get the same results?

Here's my code thanks in advance!

  void SearchBar_TextChanged(object sender, TextChangedEventArgs e)
    {
        var _Container = BindingContext as PageViewModel;
        MyListView.BeginRefresh();

        if (String.IsNullOrWhiteSpace(e.NewTextValue))
            MyListView.ItemsSource = _Container.MyPageDetailCollection;
        else
            MyListView.ItemsSource = _Container.MyPageDetailCollection.Where(i => i.Name.Contains(e.NewTextValue));
        MyListView.EndRefresh();

    }

CodePudding user response:

Consider converting strings to either lowercase/uppercase before doing the "where" LINQ query as follows:

void SearchBar_TextChanged(object sender, TextChangedEventArgs e)
{
    var _Container = BindingContext as PageViewModel;
    MyListView.BeginRefresh();

    if (String.IsNullOrWhiteSpace(e.NewTextValue))
        MyListView.ItemsSource = _Container.MyPageDetailCollection;
    else
        MyListView.ItemsSource = _Container.MyPageDetailCollection.Where(i => i.Name.ToLower().Contains(e.NewTextValue.ToLower()));
    MyListView.EndRefresh();

}

CodePudding user response:

We can first convert the input string into lower string.

You can refer to the following code:

string queryString = e.NewTextValue;

var normalizedQuery = queryString?.ToLower() ?? "";

MyListView.ItemsSource = _Container.MyPageDetailCollection.Where(f => f.Name.ToLowerInvariant().Contains(normalizedQuery)).ToList();
  • Related