Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I combine multiple linq queries into one results set?

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?

like image 378
esac Avatar asked Jul 01 '10 18:07

esac


1 Answers

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().

like image 56
Ben M Avatar answered Oct 26 '22 21:10

Ben M