Like Operator in Linq

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



Leave a reply



Submit