Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ string contains another string case insensitive

I'm working in a C# Windows 8 Metro app and I'm trying to filter an ObservableCollection<T> using LINQ where a property contains some string, and I need that it will be case insensitive.

 var searchResults = from _rest in App.ViewModel.Restaurants
                     where  _rest.Name.IndexOf(queryText,
                                 StringComparison.CurrentCultureIgnoreCase) >= 0
                     select _rest;

I work around

  • Using string1.Contains(string2).ToUpper() in both strings.
  • Using string1.Contains(string2).ToLower() in both strings.
  • Using string1.IndexOf(string2, StringComparison.CurrentCultureIgnoreCase) >= 0.
  • Using string1.IndexOf(string2, StringComparison.OrdinalIgnoreCase) >= 0.
  • Using String.Compare(string1, string2, StringComparison.CurrentCultureIgnoreCase).

But no one of this methods works for me in a case insensitive way, works ok if I write the name correctly.

Has someone have the same issue in Windows 8??

Thanks in advance for any help provided.

like image 714
Rotten Avatar asked Jun 20 '12 12:06

Rotten


People also ask

Is Linq case sensitive?

LINQ has no concept of case sensitivity, it only cares about boolean evaluation. So if you want to ignore case, you should do something like: query = query.

Is contains in C# case insensitive?

Contains() method in C# is case sensitive. And there is not StringComparison parameter available similar to Equals() method, which helps to compare case insensitive.

How use contains in Linq?

The Linq Contains Method in C# is used to check whether a sequence or collection (i.e. data source) contains a specified element or not. If the data source contains the specified element, then it returns true else return false.


1 Answers

Write you own Extension Method

public static class MetroHelper
{
    public static bool ContainsInvariant(this string mainText, string queryText)
    {
        return mainText.ToUpperInvariant().Contains(queryText.ToUpperInvariant());
    }
}

and use in your application

var searchResults = from _rest in App.ViewModel.Restaurants
                 where  _rest.Name.ContainsInvariant(queryText)
                 select _rest;

That's what I did.

like image 138
Imran Shaik Avatar answered Sep 19 '22 09:09

Imran Shaik