I have a multi-select checkbox. Depending on which one is checked, I want to combine the results into a single query. Sort of like:
if (Checkbox1.Checked)
{
var query1 = from t in table1 ...
}
if (Checkbox2.Checked)
{
var query2 = from t in table2 ...
}
DataGridView1.DataSource = query1.Union(query2); // obviously doesnt
// work since query1 and query2 are not defined in this scope.
Any idea how to combine these selectively?
Assuming the queries are of the same type, you could define the queries outside of the conditional statements.
First, a helper method that creates an empty enumerable of the same type as the parameter:
static IEnumerable<T> CreateEmptyEnumerable<T>(IEnumerable<T> templateQuery)
{
return Enumerable.Empty<T>();
}
Then, the new code:
var query1 = from t in table1 ...
var query2 = from t in table2 ...
var finalQuery = CreateEmptyEnumerable(query1);
if (Checkbox1.Checked)
{
finalQuery = query1;
}
if (Checkbox2.Checked)
{
finalQuery = finalQuery.Union(query2);
}
DataGridView1.DataSource = finalQuery.ToList(); // to avoid re-enumeration
This performs just fine because the queries aren't actually executed until they're enumerated over, as in the call to ToList()
.
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