I have a form that filters the data depending on what they select.
I am trying to append linq queries to each other so that the end result is what they have selected on the screen.
Here is my code:
private void button_Search_Click(object sender, EventArgs e)
{
using (var model = new SuburbanPortalEntities())
{
var qry = from logs in model.Logs
select logs;
Guid corpid;
if (Guid.TryParse(textBox_CorporationGuid.Text, out corpid))
{
qry = from logs in model.Logs
where logs.CorporationId == corpid
select logs;
}
Guid tokenid;
if (Guid.TryParse(textBox_TokenId.Text, out tokenid))
{
qry = from logs in model.Logs
where logs.TokenId == tokenid
orderby logs.LogDateTime descending
select logs;
}
if (checkBox_DisplayErrors.Checked)
{
qry = from logs in model.Logs
where logs.IsException
select logs;
}
if (checkBox_DisplayWarnings.Checked)
{
qry = from logs in model.Logs
where logs.IsWarning
select logs;
}
dataGridView1.DataSource = qry;
}
}
I'm having no luck. The last qry in is what is displayed on my datagridview.
Can someone show me what I'm doing wrong?
Thanks !
CORRECT ANSWER : Use the Concat method.
There are two basic ways to write a LINQ query to IEnumerable collection or IQueryable data sources.
LINQ allows us to write query against all data whether it comes from array, database, XML etc.
What's happening here is that you're redefining qry
from your source data each time. qry
is an IEnumerable<T>
just the same as logs
, so you should be able to replace your code like so:
var qry = model.Logs;
if( // Condition )
qry = qry.Where(x => x.CorporationId == corpId);
if( // Another condition)
qry = qry.Where(x => x.IsException);
At the end of this setup, qry
will be the composition of all the selected Where
clauses and should produce just the items you are looking for.
You can use linq Concat
:
qry = qry.Concat(
from logs in model.Logs
where logs.CorporationId == corpid
select logs);
On the other hand, you may want to create query based on your conditions which will select appropriate results, so you will query your data source once.
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