c# finding matching words in table column using Linq2Sql

Posted by David Liddle on Stack Overflow See other posts from Stack Overflow or by David Liddle
Published on 2010-04-11T10:47:32Z Indexed on 2010/04/11 10:53 UTC
Read the original article Hit count: 200

Filed under:
|
|
|

I am trying to use Linq2Sql to return all rows that contain values from a list of strings. The linq2sql class object has a string property that contains words separated by spaces.

public class MyObject
{
    public string MyProperty { get; set; }
}

Example MyProperty values are:

MyObject1.MyProperty = "text1 text2 text3 text4"
MyObject2.MyProperty = "text2"

For example, using a string collection, I pass the below list

var list = new List<>() { "text2", "text4" }

This would return both items in my example above as they both contain "text2" value.

I attempted the following using the below code however, because of my extension method the Linq2Sql cannot be evaluated.

public static IQueryable<MyObject> WithProperty(this IQueryable<MyProperty> qry,
    IList<string> p)
{
    return from t in qry
        where t.MyProperty.Contains(p, ' ')
        select t;
}

I also wrote an extension method

public static bool Contains(this string str, IList<string> list, char seperator)
{
    if (String.IsNullOrEmpty(str) || list == null)
        return false;

    var splitStr = str.Split(new char[] { seperator },
        StringSplitOptions.RemoveEmptyEntries);

    foreach (string s in splitStr)
        foreach (string l in list)
            if (String.Compare(s, l, true) == 0)
                return true;

    return false;
 }

Any help or ideas on how I could achieve this?

© Stack Overflow or respective owner

Related posts about c#

Related posts about linq-to-sql