Question

I have a linq statement that returns a list of records based on where clause
This where clause checks for two parameter values.
Out of which one parameter is optional.
so i need a suggestions if i can switch my where clause based on the optional Parameter
something like this

if(locid==0)
  {
   where (p.CustomerID == custid)
  }
 else{
   where (p.CustomerID == custid) & (p.LocationID == locid )
     }

can any one help me how can i get this work.

thanks

Était-ce utile?

La solution

You could try writing it like this:

where (p.CustomerID == custid) && (locid == 0 || p.LocationID == locid )

Autres conseils

Yes - queries can be composed (although you don't need this for this particular case as @rsbarro pointed out):

var query = p;

if(locid==0)
   query = query.Where( p =>p.CustomerID == custid);
else
   query = query.Where( p =>p.CustomerID == custid & p.LocationID == locid);

//any other conditions

As BrokenGlass mentioned, you should use composition:

IQueryable<Foo> query = unfiltered.Where(p => p.CustomerID == custId);
if (locid != 0)
{
    query = query.Where(p => p.LocationID == locid);
}

Note that the query is not executed until you start reading data from it, so you needn't worry about this making multiple requests.

It looks like in your original post you were trying to use query syntax piecemeal - that won't work, but the "dot notation" is pretty simple here. You can always create your initial query using a query expression if you want - again, that query won't be executed immediately anyway.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top