Linq Contains Case Insensitive

LINQ Contains Case Insensitive

Assuming we're working with strings here, here's another "elegant" solution using IndexOf().

public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM
.Where(fi => fi.DESCRIPTION
.IndexOf(description, StringComparison.OrdinalIgnoreCase) != -1);
}

Case-insensitive contains in Linq

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();

LINQ case insensitive

You want to check if Title contains the string. However, Contains itself doens't have an overload with StringComparison parameter, but you can easily do with IndexOf.

  var bookFilter = new List<Book>() {
new Book { Title = "LINQ in Action" },
new Book { Title = "LINQ for Fun" },
new Book { Title = "Extreme LINQ" } };

...

var titles = bookFilter
.Select(book => book.Title)
.Where(title => title
.IndexOf("Action", StringComparison.InvariantCultureIgnoreCase) >= 0);

LINQ To SQL Contains Case Sensitive Searching

You can transform string into lower case, using ToLower() method and then do comparison

You can also use null propagation in oder to avoid NullReference Exception in case some of the stirngs is null.

Try following

  IQueryable<article> results;
if (rrbAuthor.IsChecked)
results = (from a in _db.articles join k in _db.keywords on a.id equals k.aid
where a.author?.ToLower().Contains(textBox1.Text?.ToLower()) == true
select a).Distinct();
else if (rrbKeywords.IsChecked)
results = (from a in _db.articles join k in _db.keywords on a.id equals k.aid
where k.word?.ToLower().Contains(textBox1.Text?.ToLower()) == true
select a).Distinct();
else
results = (from a in _db.articles join k in _db.keywords on a.id equals k.aid
where a.title?.ToLower().Contains(textBox1.Text?.ToLower()) == true
select a).Distinct();
ListArticles(results, 1);

Make LINQ expression case insensitive

Will this do it? It should get the Contains method with the StringComparison parameter and pass in the value to ignore case.

MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string), typeof(StringComparison) });
var someValue = Expression.Constant(propertyValue, typeof(string));
var comparisonValue = Expression.Constant(StringComparison.OrdinalIgnoreCase, typeof(StringComparison));
var finalExpression = Expression.Call(propertyName, method, someValue, comparisonValue);


Related Topics



Leave a reply



Submit