Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I append LINQ queries to each other?

Tags:

c#

linq

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 !

like image 595
ErocM Avatar asked Aug 09 '13 14:08

ErocM


People also ask

How you can merge the results from two separate LINQ queries into a single result set?

CORRECT ANSWER : Use the Concat method.

What are the two types of LINQ queries?

There are two basic ways to write a LINQ query to IEnumerable collection or IQueryable data sources.

Can LINQ query work with Array?

LINQ allows us to write query against all data whether it comes from array, database, XML etc.


2 Answers

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.

like image 95
Tejs Avatar answered Sep 19 '22 05:09

Tejs


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.

like image 21
Zbigniew Avatar answered Sep 21 '22 05:09

Zbigniew