Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 721091
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T05:50:02+00:00 2026-05-14T05:50:02+00:00

I am trying to use Linq2Sql to return all rows that contain values from

  • 0

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 (str == null) return false;
    if (list == null) return true;

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

    bool retval = false;
    int matches = 0;

    foreach (string s in splitStr)
    {
        foreach (string l in list)
        {
            if (String.Compare(s, l, true) == 0)
            {
                retval = true;
                matches++;
            }
        }
    }

    return retval && (splitStr.Length > 0) && (list.Count == matches);
 }

Any help or ideas on how I could achieve this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T05:50:02+00:00Added an answer on May 14, 2026 at 5:50 am

    Youre on the right track. The first parameter of your extension method WithProperty has to be of the type IQueryable<MyObject>, not IQueryable<MyProperty>.

    Anyways you dont need an extension method for the IQueryable. Just use your Contains method in a lambda for filtering. This should work:

    List<string> searchStrs = new List<string>() { "text2", "text4" }
    
    IEnumerable<MyObject> myFilteredObjects = dataContext.MyObjects
                       .Where(myObj => myObj.MyProperty.Contains(searchStrs, ' '));
    

    Update:

    The above code snippet does not work. This is because the Contains method can not be converted into a SQL statement. I thought a while about the problem, and came to a solution by thinking about ‘how would I do that in SQL?’: You could do it by querying for each single keyword, and unioning all results together. Sadly the deferred execution of Linq-to-SQL prevents from doing that all in one query. So I came up with this compromise of a compromise. It queries for every single keyword. That can be one of the following:

    • equal to the string
    • in between two seperators
    • at the start of the string and followed by a seperator
    • or at the end of the string and headed by a seperator

    This spans a valid expression tree and is translatable into SQL via Linq-to-SQL. After the query I dont defer the execution by immediatelly fetch the data and store it in a list. All lists are unioned afterwards.

    public static IEnumerable<MyObject> ContainsOneOfTheseKeywords(
            this IQueryable<MyObject> qry, List<string> keywords, char sep)
    {
        List<List<MyObject>> parts = new List<List<MyObject>>();
    
        foreach (string keyw in keywords)
            parts.Add((
                from obj in qry
                where obj.MyProperty == keyw ||
                      obj.MyProperty.IndexOf(sep + keyw + sep) != -1 ||
                      obj.MyProperty.IndexOf(keyw + sep) >= 0 ||
                      obj.MyProperty.IndexOf(sep + keyw) ==
                          obj.MyProperty.Length - keyw.Length - 1
                select obj).ToList());
    
        IEnumerable<MyObject> union = null;
        bool first = true;
        foreach (List<MyObject> part in parts)
        {
            if (first)
            {
                union = part;
                first = false;
            }
            else
                union = union.Union(part);
        }
    
        return union.ToList();
    }
    

    And use it:

    List<string> searchStrs = new List<string>() { "text2", "text4" };
    
    IEnumerable<MyObject> myFilteredObjects = dataContext.MyObjects
                        .ContainsOneOfTheseKeywords(searchStrs, ' ');
    

    That solution is really everything else than elegant. For 10 keywords, I have to query the db 10 times and every time catch the data and store it in memory. This is wasting memory and has a bad performance. I just wanted to demonstrate that it is possible in Linq (maybe it can be optimized here or there, but I think it wont get perfect).

    I would strongly recommend to swap the logic of that function into a stored procedure of your database server. One single query, optimized by the database server, and no waste of memory.

    Another alternative would be to rethink your database design. If you want to query contents of one field (you are treating this field like an array of keywords, seperated by spaces), you may simply have chosen an inappropriate database design. You would rather want to create a new table with a foreign key to your table. The new table has then exactly one keyword. The queries would be much simpler, faster and more understandable.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to use reflection to automatically test that all my linq2sql entities match
I have been trying use the edit_post_link() function to contain an image. All of
I have a regex that I'm trying use to validate against strings. Trying to
I am trying use a from a multi-dimensional array that I create in another
I'm trying use mod_rewrite to rewrite URLs from the following: http://www.site.com/one-two-file.php to http://www.site.com/one/two/file.php The
I am trying use filehelpers class builder but I am kinda confused on what
I am trying use std::copy to copy from two different iterator. But during course
I'm trying use to selenium with firefox on CentOS from command line like this:
I'm trying to use t4toolbox to generate the linq2sql classes for a project. There
i'm trying use webview to load a image from sdcard i use this path

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.