assume I have customer table with ( name column and number column) user can do query to display the one name's number or display all number if there is no restrict ;
this example
void DisplayNumbersOfName(string name)
{
using (dataclassDataContext db = new dataclassDataContext())
{
if(name=="")
var Names = from ta in db.table_accounts
select ( ta );
else
Names = from ta in db.table_accounts
where ta.name = name
select ( ta );
}
}
I don't want use this way because the method is
more complex , I want only change on 'where ' WHERE with IF
You should use the fact that LINQ queries compose nicely - and that you don't need to use the query expression syntax. So:
// Fixing naming conventions as I go, to make the code more idiomatic...
using (DataClassDataContext db = new DataClassDataContext())
{
IQueryable<YourDataType> query = db.TableAccounts;
if (name != "")
{
query = query.Where(ta => ta.Name == name);
}
// Use query here...
}
walther's solution is another viable alternative, but it does mean evaluating the "do we really want this as part of the query" in the database - you'll end up with SQL which is somewhat harder to understand. Personally I prefer to be explicit about whether you want a particular filter to be part of the query.
void DisplayNumbersOfName(string name)
{
using (dataclassDataContext db = new dataclassDataContext())
{
var Names = from ta in db.table_accounts
where (String.IsNullOrEmpty(name) || ta.name == name)
select ( ta );
}
}
Haven't checked it to be honest, but it should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With