Aboud Zakaria
Aboud Zakaria

Reputation: 567

Entity Framework Filtering with a List of String

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.

Upvotes: 3

Views: 6103

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

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.

Upvotes: 6

Pleun
Pleun

Reputation: 8920

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))

Upvotes: 5

Related Questions