Case insensitive "contains" in Linq
I have an mvc project where I am using linq. There are some records in my database like "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 will return 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 the help...
+3
source to share
4 answers
the easy way is to use the ToLower () method
var lists = rec.Where(p => p.Name.ToLower().Contains(records.Name.ToLower())).ToList();
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();
+10
source to share
use IndexOf
and StringComparison.OrdinalIgnoreCase
:
p.Name.IndexOf(records.Name, StringComparison.OrdinalIgnoreCase) >= 0;
You can create an extension function like this:
public static bool Contains(this string src, string toCheck, StringComparison comp)
{
return src.IndexOf(toCheck, comp) >= 0;
}
+2
source to share