Use SQL LIKE operator in C# LINQ
There are lots of possibilities for Like in Linq:
For LIKE '%abc%';
list.Where(x => x.myTextColumn.Contains('abc'));
For LIKE 'abc%';
list.Where(x => x.myTextColumn.StartWith('abc'));
For LIKE '%abc';
list.Where(x => x.myTextColumn.EndsWith('abc'));
Updates : If you need to add Date comparison as well means you can do like the following:
DateTime date2Compare = new DateTime(2017, 1, 20);
list.Where(x => myDateColumn >= date2Compare && x.myTextColumn.Contains('abc'));
Like operator in LINQ to Objects
I don't know of one that readily exists, but if you're familiar with regular expressions, you can write your own:
using System;
using System.Text.RegularExpressions;
public static class MyExtensions
{
public static bool Like(this string s, string pattern, RegexOptions options = RegexOptions.IgnoreCase)
{
return Regex.IsMatch(s, pattern, options);
}
}
And then in your code:
string pattern = ".*ine.*e";
var res = from i in list
where i.Like(pattern)
select i;
How to use LIKE Operator in LINQ to Entity Framework
Do like this.
var result
= dbContext.Categories.Where(i => i.CategoryName.StartsWith("a")).ToList();
How to do a LIKE query with linq?
You could use SqlMethods.Like(matchExpression,pattern)
var results = from c in db.costumers
where SqlMethods.Like(c.FullName, "%"+FirstName+"%,"+LastName)
select c;
The use of this method outside of LINQ to SQL will always throw a NotSupportedException exception.
How to do SQL Like % in Linq?
.Where(oh => oh.Hierarchy.Contains("/12/"))
You can also use .StartsWith()
or .EndsWith()
.
What is the SQL LIKE operator equivalent in LINQ having multiple % operators in the input text?
Posting the comments given by @Fabio and @CodeNotFound as answer for reference.
In EntityFramework version 6.2.0:
var users = (from usr in Context.Users
where DbFunctions.Like(usr.Username, "%test%email%")
select usr).ToList();
Related Topics
ASP.NET MVC Dropdownlistfor with Model of Type List<String>
What Is the Correct Way to Read a Serial Port Using .Net Framework
App.Config for a Class Library
Nice & Universal Way to Convert List of Items to Tree
Md5 Hash with Salt for Keeping Password in Db in C#
Am I Misunderstanding Linq to SQL .Asenumerable()
In .Net/C# Test If Process Has Administrative Privileges
How to Read the Data in a Wav File to an Array
Asp .Net MVC Disable Client Side Validation at Per-Field Level
How to Prevent Windows from Entering Idle State
C# How to Test a File Is a Jpeg
Meanings of Declaring, Instantiating, Initializing and Assigning an Object
Possible to Iterate Backwards Through a Foreach
Struct Constructor: "Fields Must Be Fully Assigned Before Control Is Returned to the Caller."
In Wpf Can You Filter a Collectionviewsource Without Code Behind