genxgeek
genxgeek

Reputation: 13357

LINQ/Projection - Contains all wildcard for filtering

Is there an equivalent "*" for Contains("")? I'm using some wildcards for filtering and if there isn't a filter applied then I need to return all?

string[] filter = {1,2};  // This is dynamic could be filtered values or {} empty.

// This works for filtering by products (1,2)
db.Products.Where(x => filter.Contains(x.ProdId));

What I really need to achieve is something like this:

// If the filter is empty get all results...if there is a filter passed the filter values in for select
db.Products.Where(x => x.ProdId.Contains(filter.Length == 0 ? "*" : filter);

Upvotes: 1

Views: 1306

Answers (3)

Seattle Leonard
Seattle Leonard

Reputation: 6776

db.Products.Where(x => !filter.Any() || filter.Contains(x.ProdId))

Although I like the other answers listed :

if(filter.Any()) result = result.Where(x => filter.Contains(x.ProdId));

In the first example, it will loop through the collection and determine that the filter does have items for every item in the result. The second will only loop if there are items in the filter

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

Use this:

var result = db.Products.AsQueryable();

if(filter.Any())
    result = result.Where(x => filter.Contains(x.ProdId));

If the filter is not the only where condition, that's not a problem at all, you can define multiple Wheres for your query:

var result = db.Products.Where(x => SomeCondition(x));

if(filter.Any())
    result = result.Where(x => filter.Contains(x.ProdId));

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564403

You can just add the where, if necessary:

var query = db.Products.AsQueryable();
if (filter.Any())
    query = query.Where(x => filter.Contains(x.ProdId));

// use query as needed

Upvotes: 3

Related Questions