1

1

I want to join two queries into one, how can I do this?

For example:

Query #1:

query = query.Where(q => q.Currency == filter.Currency)

Query #2:

query = query.Where(n => n.FirstName == filter.FirstName)

As a result ,I want to get

query = query.Where(k => k.Currency == filter.Currency && 
                         k.FirstName == filter.FirstName)

Queries are created dynamically, they can include many conditions.


update:

I have a two search types and they can work together. And in the first part there may be several conditions, and in the second one too. The second filter can include two parts with "and" "or"

Peter Csala
  • 17,736
  • 16
  • 35
  • 75

1 Answers1

0

I think what you could try is to have two predicates instead of two queries. Sample:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
  public static void Main()
  {
    var pred1 = new Func<int, bool>(f => f % 2 == 0);
    var pred2 = new Func<int, bool>(f => f % 3 == 0);
    foreach (var i in Fibonacci().Take(20).Where(pred1).Where(pred2))
    {
      Console.WriteLine(i);
    }
  }

  private static IEnumerable<int> Fibonacci()
  {
    int current = 1, next = 1;

    while (true) 
    {
      yield return current;
      next = current + (current = next);
    }
  }
}
Neeraj
  • 596
  • 7
  • 9
  • Just read , the expressions example it works better for dynamic chaining. https://stackoverflow.com/questions/457316/combining-two-expressions-expressionfunct-bool – Neeraj May 20 '22 at 08:51