Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case-insensitive "contains" in Linq

Tags:

c#

linq

I have a mvc project which I use linq in it. In my database there is some records, for example "Someth ing","SOmeTH ing","someTh ing","SOMETH ING","someTH ING"

I want to do this:

SELECT * FROM dbo.doc_dt_records WHERE name LIKE '%' + @records.Name + '%'

However if I run this code, list.Count returns 0. What should I do?

    records.Name = "someth ing"; //for example
    var rec = db.Records.ToList();
         var lists = rec.Where(p => p.Name.Contains(records.Name)).ToList();
if (lists.Count > 0)
{
    // do sthng
}

Thanks for your helps...

like image 310
Bilal Avatar asked Nov 24 '14 14:11

Bilal


People also ask

Is Contains case sensitive LINQ?

LINQ StartsWith , EndsWith , and Contains are case sensitive and return false if two same string s are of different cases, e.g., " STRING " and " string ".

How do you make a LINQ query case insensitive?

Use string. Equals(name, article.Name, StringComparison. OrdinalIgnoreCase) when you are sure that your database supports it. E.g. SQLite with a collate of NOCASE will ignore the option.

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.

Is EF core case sensitive?

For one thing, EF Core does know not which case-sensitive or case-insensitive collation should be used. More importantly, applying a collation would in most cases prevent index usage, significantly impacting performance for a very basic and commonly-used . NET construct.


2 Answers

the easy way is to use ToLower() method

var lists = rec.Where(p => p.Name.ToLower().Contains(records.Name.ToLower())).ToList();

a better solution (based on this post: Case insensitive 'Contains(string)')

 var lists = rec.Where(p => 
             CultureInfo.CurrentCulture.CompareInfo.IndexOf
             (p.Name, records.Name, CompareOptions.IgnoreCase) >= 0).ToList();
like image 196
ymz Avatar answered Sep 19 '22 12:09

ymz


That is totally not a LINQ issue.

Case sensitiivty on the generated SQL depends on the collation relevant for the table. Which in your case likely is case insensitive.

You would get the same result from any SQL you emit.

like image 42
TomTom Avatar answered Sep 21 '22 12:09

TomTom