3

I want to filter results According to List of strings, something like this:

List<string> filters = {"a", "b", "c", "d"};
var results = (from R in db.Entries 
               where R.word.StartsWith(filters[0])
               ||R.word.StartsWith(filters[1])
               ||R.word.StartsWith(filters[2])
               ||...

I don't know the Length of my filters List so how to Query it dynamically in LINQ?

Thanks in advance.

1
  • yup, they are single letters. Commented Mar 28, 2015 at 11:46

2 Answers 2

6

You should be able to do it like this:

var results = db.Entries 
    .Where(r => filters.Any(f => r.word.StartsWith(f)));

Extension method Any is a way to "fold" a chain of ORs || applied to a list into a single call.

Sign up to request clarification or add additional context in comments.

1 Comment

You could also replace Any with All. Any behave like OR and All more like AND.
5

This works a little bit different in Linq, kind of the other way around

Use the .Contains()

Something like this:

from r in db.entries
where filters.contains (r.word.substring(0,1))

2 Comments

this works great!, but I'm wondering does calling substring(0,1) for every word in database costs much time? I think I will have a performance issue (Entries table contains more than 100k words)
You can check the gernerated SQL in Linq to sql

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.