Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use a string for a LINQ query expression?

I need to extract some records if some variables have some values.

For example, if status>0 I need to filter result like :

where object.id=status

else, if status=0, I need to remove this where clauses and return all elements. I'll get rid about :

if(status>0)
   do a linq query with the where clauses
else
   do a link query with that where clauses

too much code, because the variables to check could be more than 4-5.

Is it possible to "inject" a sort of string on LINQ? (So i can create my string and pass it to the LINQ).

I mean somethings like :

string myQuery="";
if(status>0)
   myQuery="where object.id=status";
else
   myQuery="";

is it possible? (Classic mysql behaviour).

like image 902
markzzz Avatar asked Jul 27 '11 15:07

markzzz


People also ask

Can you use LINQ on a string?

LINQ can be used to query and transform strings and collections of strings. It can be especially useful with semi-structured data in text files. LINQ queries can be combined with traditional string functions and regular expressions.

What is the data type for Linq query?

There is no single datatype for LINQ queries as it depends on the context. In your case you are selecting "Car" so the datatype is going to be IQueryable. As pointed out in the comments you can hold your mouse over any var (not just those involving LINQ queries) to get the datatype.

Which of the following clauses can be used to end a LINQ query expression?

LINQ query syntax always ends with a Select or Group clause.

What is query expression in LINQ?

C# Query Expression is an expression that is written by using LINQ query syntax. The LINQ (Language Integrated Query) is a language that is used to construct a query. C# Query Expression contains set of clauses and use query expression similar to SQL.


1 Answers

Since LINQ is lazy, you can just do

var query = ...

if (status > 0)
{
    query = query.Where(o => o.id == status);
}
like image 50
hammar Avatar answered Nov 15 '22 17:11

hammar