Reputation: 4662
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 !
Upvotes: 6
Views: 7831
Reputation: 27584
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.
Upvotes: 6
Reputation: 1989
Try using Concat:
private void button_Search_Click(object sender, EventArgs e)
{
using (var model = new SuburbanPortalEntities())
{
var qry = (from logs in model.Logs
select logs).ToList();
Guid corpid;
if (Guid.TryParse(textBox_CorporationGuid.Text, out corpid))
{
qry.Concat((from logs in model.Logs
where logs.CorporationId == corpid
select logs).ToList());
}
Guid tokenid;
if (Guid.TryParse(textBox_TokenId.Text, out tokenid))
{
qry.Concat(from logs in model.Logs
where logs.TokenId == tokenid
orderby logs.LogDateTime descending
select logs).ToList());
}
if (checkBox_DisplayErrors.Checked)
{
qry.Concat((from logs in model.Logs
where logs.IsException
select logs).ToList());
}
if (checkBox_DisplayWarnings.Checked)
{
qry.Concat((from logs in model.Logs
where logs.IsWarning
select logs).ToList());
}
dataGridView1.DataSource = qry;
} }
Upvotes: 0
Reputation: 41236
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.
Upvotes: 11