KallDrexx
KallDrexx

Reputation: 27813

How can I check if a string in sql server contains at least one of the strings in a local list using linq-to-sql?

In my database field I have a Positions field, which contains a space separated list of position codes. I need to add criteria to my query that checks if any of the locally specified position codes match at least one of the position codes in the field.

For example, I have a local list that contains "RB" and "LB". I want a record that has a Positions value of OL LB to be found, as well as records with a position value of RB OT but not records with a position value of OT OL.

With AND clauses I can do this easily via

foreach (var str in localPositionList)
    query = query.Where(x => x.Position.Contains(str);

However, I need this to be chained together as or clauses. If I wasn't dealing with Linq-to-sql (all normal collections) I could do this with

query = query.Where(x => x.Positions.Split(' ').Any(y => localPositionList.contains(y)));

However, this does not work with Linq-to-sql as an exception occurs due it not being able to translate split into SQL.

Is there any way to accomplish this?

I am trying to resist splitting this data out of this table and into other tables, as the sole purpose of this table is to give an optimized "cache" of data that requires the minimum amount of tables in order to get search results (eventually we will be moving this part to Solr, but that's not feasible at the moment due to the schedule).

Upvotes: 0

Views: 773

Answers (1)

vansimke
vansimke

Reputation: 974

I was able to get a test version working by using separate queries and running a Union on the result. My code is rough, since I was just hacking, but here it is...

        List<string> db = new List<string>() {
            "RB OL",
            "OT LB",
            "OT OL"
        };

        List<string> tests = new List<string> {
            "RB", "LB", "OT"
        };

        IEnumerable<string> result = db.Where(d => d.Contains("RB"));

        for (int i = 1; i < tests.Count(); i++) {
            string val = tests[i];
            result = result.Union(db.Where(d => d.Contains(val)));
        }

        result.ToList().ForEach(r => Console.WriteLine(r));

        Console.ReadLine();

Upvotes: 1

Related Questions