Below is the sample code, pls solve my problem. I need where
bool filterOnFirstName =true; and bool filterOnLastName
= true; how to write Where clause dynamically for "AND" expression in below way..
pls note that sometime filterOnFirstName or filterOnLastName will be true and false in all combination
subhankarpan...
Member
63 Points
49 Posts
Dymanic Linq in Where clause in DataTable
Dec 09, 2012 07:18 AM|LINK
Below is the sample code, pls solve my problem. I need where bool filterOnFirstName = true; and bool filterOnLastName = true;
how to write Where clause dynamically for "AND" expression in below way..
pls note that sometime filterOnFirstName or filterOnLastName will be true and false in all combination
Please help
table = new DataTable("People");
table.Columns.Add("Firstname", typeof (string));
table.Columns.Add("Lastname", typeof (string));
table.Rows.Add(new object[] {"John", "Doe"});
table.Rows.Add(new object[] {"Jane", "Doe"});
table.Rows.Add(new object[] {"Donald", "Duck"});
table.Rows.Add(new object[] {"Jumping", "Jack"});
bool filterOnFirstName = true;
bool filterOnLastName = true;
var query = table.AsEnumerable();
if (filterOnFirstName)
{ query = query.Where(r => ((string) r["Firstname"]).StartsWith("J"));
}
if (filterOnLastName)
{
query = query.Where(r => ((string) r["Lastname"]).StartsWith("J"));
}
var queryFinal = from q in query
select new {FullName = q.Field<string>("Firstname") + " " + q.Field<string>("Lastname")};
GridView1.DataSource = queryFinal;
GridView1.DataBind();
Subhankar
Decker Dong ...
All-Star
118619 Points
18779 Posts
Re: Dymanic Linq in Where clause in DataTable
Dec 10, 2012 01:18 AM|LINK
Hi,
As far as I see, your codes seem right.
Because if one condition is OK, you will use the extended method "Where" to do a filtering records.
And once another one fits, you will apply another "Where" to the firstly-filtered result.