tags:

views:

27

answers:

1

I have a list of keywords in an ArrayList and I wanted to be able to build a query to find records in a table based on this keywords.

Since the list of keywords is dynamic I cannot build a fixed query here.

I do something like this:

foreach (string kw in keywords)
{
  query = query.Where(p => p.Name.StartsWith(kw));
}

The "StartsWith" is required here because I need to search those records that actually start with the provided keyword.

In T-SQL it Would be something like this

Select * from Table where 
Name like 'keyword1%' 
or Name like 'keyword2%'
or Name like 'keyword3%'
or ...

But I need to be able to do this in LINQ...Is this possible?

+1  A: 

This oughtta do it:

var query = table.Where(p => keywords.Any(kw => p.Name.StartsWith(kw)));
tzaman
I wonder if LINQ to SQL is actually that smart. I know EF3.5 would miserably fail with such a query. Still my +1.
Steven
Using this I get the ""Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator." exception...
Bathan
@Bathan: Huh; I guess @Steven's right then - L2S isn't smart enough for this. Unfortunately, I can't really see an easy way to rewrite it using `Contains`...
tzaman
The above sentence is wrong, but even if corrected, L2S doesn’t know what to do with it. As you’ve said, it’s not smart enough.
Martín Marconcini