Is it possible to use list in where. I want somethink like this:
public class Customer
{
string FirtsName;
string LastName;
int Number;
.....
}
I want to filter customers with using checkboxes. If I select FirstName and Number then where clause will be generated
.where(x=> x.FirstName == "SomeFirstName" && x.Number == someNumber)
If I select only number then where clause will be generated
.where(x.Number == someNumber)
If I select FirstName, LastName and Number then where clause will be generated
.where(x=> x.FirstName == "SomeFirstName" && x.Number == someNumber && x.LastName == "LastName")
I mean not only dynamic column names, also I want to generate where clauses count, too. Column names and values are came from list:
I hope, I can explain. Thanks in advance.
You could give Dynamic LINQ a try. With this you could write something like:
var db = new NorthwindDataContext;
var query = db.Products.Where("CategoryID=2 And UnitPrice>3").OrderBy("SupplierId");
Use more then one step to generate the query:
var query = originalList.AsQueryable();
if(/*Filtering on First Name*/)
{
query = query.where(x => x.FirstName == FirstNameSearchString);
}
if(/*Filtering on Last Name */)
{
query = query.where(x => x.LastName == LastNameSearchString);
}
if(/*Filtering on Number*/)
{
query = query.where(x => x.Number== NumberSearchString);
}
//..And so on
//Do stuff with query
If you don't want to do the multiple if statements I can think of two other ways:
Expression Trees (C# and Visual Basic) How to: Use Expression Trees to BUild Dynamic Queries (C# and Visual Basic)
The other method is to create a complex where clause that used ANDs and ORs to only filter if this column searc option is selected:
.where(x => (IsFirstNameFilter == true && x.FirstName = FirstNameData) || (IsLastNameFilter == true && x.LastName = LastNameData) || ...);
With this one, you want to be careful about the execution time, hook up SQL Profiler to see what is happening.
I still recommend the first option.