score:9
so, if flag
is false
you need all jhoms, and if flag
is true you need only the jhoms in the it department
this condition
!flag || (e.field<string>("employeedepartment") == "it"
satisfies that criterion (it's always true if flag is false, etc..), so the query will become:
from e in employee
where e.field<string>("employeename") == "jhom"
&& (!flag || (e.field<string>("employeedepartment") == "it")
select e.field<string>("employeeid")
also, this e.field<string>("employeeid")
business, smells like softcoding, might take a look into that. i guess
from e in employee
where e.employeename == "jhom"
&& (!flag || (e.employeedepartment == "it")
select e.employeeid
would be more compact and less prone to typing errors.
edit: this answer works for this particular scenario. if you have lots of this kinds of queries, by all means investingate the patterns proposed in the other answers.
score:0
from e in employee
where e.field<string>("employeename") == "jhom" &&
(!flag || e.field<string>("employeedepartment") == "it")
select e.field<string>("employeeid")
score:0
you can call linq methods explicitly and chain them conditionally.
public ienumerable<string> filteremployees (ienumerable<employee> source, bool restrictdepartment)
{
var query = source.where (e => e.field<string>("employeename") == "jhom");
if (restrictdepartment) // btw, there's no need for "== true"
query = query.where (e => e.field<string>("employeedepartment") == "it");
return query.select (e => e.field<string>("employeeid"));
}
score:2
you can chain methods :
public void test(bool flag)
{
var res = employee.where( x => x.employeename = "jhom" );
if (flag)
{
res = res.where( x => x.employeedepartment == "it")
}
var id = res.select(x => x.employeeid );
}
score:12
please check out the full blog post: dynamic query with linq
there are two options you can use:
string condition = string.empty;
if (!string.isnullorempty(txtname.text))
condition = string.format("name.startswith(\"{0}\")", txtname.text);
employeedatacontext edb = new employeedatacontext();
if(condition != string.empty)
{
var emp = edb.employees.where(condition);
///do the task you wnat
}
else
{
//do the task you want
}
predicate builder works similar to dynamic linq library but it is type safe:
var predicate = predicatebuilder.true<employee>();
if(!string.isnullorempty(txtaddress.text))
predicate = predicate.and(e1 => e1.address.contains(txtaddress.text));
employeedatacontext edb= new employeedatacontext();
var emp = edb.employees.where(predicate);
difference between above library:
- predicatebuilder allows to build typesafe dynamic queries.
- dynamic linq library allows to build queries with dynamic where and orderby clauses specified using strings.
Source: stackoverflow.com
Related Query
- Dynamic where condition in LINQ
- LINQ where condition with dynamic column
- How to embed dynamic OR condition after WHERE statement in linq query c#
- Where condition with linq dynamic built at runtime to read xml
- Dynamic where condition in linq query expression
- How to create a Dynamic Query when there's a condition that won't use all fields in the where section with LinQ
- Entity Framework dynamic linq where from generic source with dynamic where clause
- Dynamic where condition LINQ
- Dynamic WHERE clause in LINQ
- If condition in LINQ Where clause
- LINQ Where with AND OR condition
- LINQ query to perform a projection, skipping or wrapping exceptions where source throws on IEnumerable.GetNext()
- Dynamic where clause (OR) in Linq to Entities
- NHibernate efficient Delete using LINQ Where condition
- Dynamic where clause in Linq to Entities
- LINQ WHERE method alters source collection
- Where can I view LINQ source code?
- How to specify dynamic field names in a Linq where clause?
- LINQ where condition filtering
- C# Dynamic Linq Variable Where clause
- Linq Where condition to match array
- Dynamically Modifying Where Condition in LINQ Query
- Building a dynamic where clause for dynamic keywords or using IQueryable C# Linq
- Dynamic Where Clause over relational tables with LINQ to SQL
- linq query with dynamic predicates in where clause joined by OR
- Linq to Sql with lambda sum as a where condition
- LINQ Source Code Available
- Linq : How do I test a List<bool> for condition where any one of its values == true?
- How do I create a where condition on a sub table in LINQ
- Left/outer join with linq on c# with where condition clause
More Query from same tag
- Select child record in relation two tables
- Using "in" operator in where clause of entity framework
- LINQ Query to identify fragments in a series
- Linq how to union array of objects inside list and group by value
- LINQ DataTables
- How can I distinct with condition?
- How to increment column with last column value in Lambda or Linq
- Creating a collection of a particular property of all the elements of a collection without iterating the elements of that collection
- Combine expressions for Where statement
- Read data from more than one table using Azure Mobile Services
- How to properly test float or double for quality and other comparisons
- How to return a list of stores which are a specified distance from the entered Postcode
- LINQ INNER SELECT WITH TOP
- Asp.net mvc Linq query for multiple filters
- How to use AND operator in LINQ Join
- Is it possible to create ICriteria/ICriterion from LINQ or HQL?
- Matching users who reviewed the same restaurants
- Linq Order and Group 2 Items in a List by Name
- Linqpad query error
- LINQ - join the highest rank picture of a product that has many pictures
- LINQ select new list, pass parent class to property class
- Fill correctly a IQueryable model with linq join
- Help convert SQL statement to LINQ Lambda (need help with group by and sum)
- multiple groupby using operator in linq display differently from using expression
- Entity Framework String Condition At List That Linked With ForeignKey
- Performance difference between Linq Select and ToList
- LINQ select: want to pass collection into CONTAINS
- Use Compiled Lambda expression instead of Activator.CreateInstance to initialize SoapHttpClientProtocol object
- Using the same linq when switching EF database
- How to get a list of filtered values in Dictionary into a List using LINQ or Lambda?