Marco
Marco

Reputation: 1272

Dynamic where in LINQ

Hi I have this LINQ query:

var q =
    (from vr in Util.db.ValuationsRequests
     where vr.dtSubmitted != null
     select vr
     ).AsEnumerable<ValuationsRequest>();

But I want to do a search with 3 more parameters: paramValuationId (int), paramValue (boolean), paramTitle (string).

Something like:

if (paramTitle != string.empty)
//add this field to the where

But if the paramTitle is empty I do not want to search for it.

What is the correct way of doing this?

Upvotes: 2

Views: 204

Answers (2)

John Hartsock
John Hartsock

Reputation: 86872

string paramTitle = "hello";
var q =
    (from vr in Util.db.ValuationsRequests
     where vr.dtSubmitted != null 
       && ( paramTitle == "" || vr.paramTitle == paramTitle)
     select vr
     ).AsEnumerable<ValuationsRequest>();

Upvotes: 5

Jeffrey Lott
Jeffrey Lott

Reputation: 7419

var q =
(from vr in Util.db.ValuationsRequests
 where vr.dtSubmitted != null
 select vr
 ).AsEnumerable<ValuationsRequest>();

if(!string.IsNullOrEmpty(paramTitle))
   q = q.Where(p => p.ParamTitle == paramTitle);

Upvotes: 2

Related Questions