Search code examples
c#linq-to-objectssql-like

Like operator in LINQ to Objects


I'm trying to emulate the LIKE operator in LINQ to Objects. Here my code:

List<string> list = new List<string>();
list.Add("line one");
list.Add("line two");
list.Add("line three");
list.Add("line four");
list.Add("line five");
list.Add("line six");
list.Add("line seven");
list.Add("line eight");
list.Add("line nine");
list.Add("line ten");

string pattern = "%ine%e";

var res = from i in list
            where System.Data.Linq.SqlClient.SqlMethods.Like(i, pattern)
              select i;

It did not get me result because of System.Data.Linq.SqlClient.SqlMethods.Like is only for translation into SQL.

Does anything similar to sql LIKE operator exists in LINQ to Objects world?


Solution

  • 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;