title: LINQ Expression Tree Any() inside Where()
body: <p>I'm trying to generate the following LINQ query:</p>
  
  <pre class="lang-cs prettyprint-override"><code>//Query the database for all AdAccountAlerts that haven't had notifications sent out
  //Then get the entity (AdAccount) the alert pertains to, and find all accounts that
  //are subscribing to alerts on that entity.
  var x = dataContext.Alerts.Where(a =&gt; a.NotificationsSent == null)
    .OfType&lt;AdAccountAlert&gt;()
    .ToList()
    .GroupJoin(dataContext.AlertSubscriptions,
      a =&gt; new Tuple&lt;int, string&gt;(a.AdAccountId, typeof(AdAccount).Name),
      s =&gt; new Tuple&lt;int, string&gt;(s.EntityId, s.EntityType),
      (Alert, Subscribers) =&gt; new Tuple&lt;AdAccountAlert, IEnumerable&lt;AlertSubscription&gt;&gt; (Alert, Subscribers))
    .Where(s =&gt; s.Item2.Any())
    .ToDictionary(kvp =&gt; (Alert)kvp.Item1, kvp =&gt; kvp.Item2.Select(s =&gt; s.Username));
  </code></pre>
  
  <p>Using Expression Trees (which seems to be the only way I can do this when I need to use reflection and run-time types). Note that in the real code (see below) the AdAccountAlert is actually dynamic through reflection and a for-loop.</p>
  
  <p><strong>My problem</strong>: I can generate everything up to the .Where() clause. The whereExpression method call blows up because of incompatible types. Normally I know what to put there, but the Any() method call has me confused. I've tried every type I can think of and no luck. Any help with both the .Where() and .ToDictionary() would be appreciated.</p>
  
  <p>Here's what I have so far:</p>
  
  <pre class="lang-cs prettyprint-override"><code>var alertTypes = AppDomain.CurrentDomain.GetAssemblies()
    .Single(a =&gt; a.FullName.StartsWith("Alerts.Entities"))
    .GetTypes()
    .Where(t =&gt; typeof(Alert).IsAssignableFrom(t) &amp;&amp; !t.IsAbstract &amp;&amp; !t.IsInterface);
  
  var alertSubscribers = new Dictionary&lt;Alert, IEnumerable&lt;string&gt;&gt;();
  
  //Using tuples for joins to keep everything strongly-typed
  var subscribableType = typeof(Tuple&lt;int, string&gt;);
  var doubleTuple = Type.GetType("System.Tuple`2, mscorlib", true);
  
  foreach (var alertType in alertTypes)
  {
    Type foreignKeyType = GetForeignKeyType(alertType);
    if (foreignKeyType == null)
      continue;
  
    IQueryable&lt;Alert&gt; unnotifiedAlerts = dataContext.Alerts.Where(a =&gt; a.NotificationsSent == null);
  
    //Generates: .OfType&lt;alertType&gt;()
    MethodCallExpression alertsOfType = Expression.Call(typeof(Enumerable).GetMethod("OfType").MakeGenericMethod(alertType), unnotifiedAlerts.Expression);
  
    //Generates: .ToList(), which is required for joins on Tuples
    MethodCallExpression unnotifiedAlertsList = Expression.Call(typeof(Enumerable).GetMethod("ToList").MakeGenericMethod(alertType), alertsOfType);
  
    //Generates: a =&gt; new { a.{EntityId}, EntityType = typeof(AdAccount).Name }
    ParameterExpression alertParameter = Expression.Parameter(alertType, "a");
    MemberExpression adAccountId = Expression.Property(alertParameter, alertType.GetProperty(alertType.GetForeignKeyId()));
    NewExpression outerJoinObject = Expression.New(subscribableType.GetConstructor(new Type[] { typeof(int), typeof(string)}), adAccountId, Expression.Constant(foreignKeyType.Name));
    LambdaExpression outerSelector = Expression.Lambda(outerJoinObject, alertParameter);
  
    //Generates: s =&gt; new { s.EntityId, s.EntityType }
    Type alertSubscriptionType = typeof(AlertSubscription);
    ParameterExpression subscriptionParameter = Expression.Parameter(alertSubscriptionType, "s");
    MemberExpression entityId = Expression.Property(subscriptionParameter, alertSubscriptionType.GetProperty("EntityId"));
    MemberExpression entityType = Expression.Property(subscriptionParameter, alertSubscriptionType.GetProperty("EntityType"));
    NewExpression innerJoinObject = Expression.New(subscribableType.GetConstructor(new Type[] { typeof(int), typeof(string) }), entityId, entityType);
    LambdaExpression innerSelector = Expression.Lambda(innerJoinObject, subscriptionParameter);
  
    //Generates: (Alert, Subscribers) =&gt; new Tuple&lt;Alert, IEnumerable&lt;AlertSubscription&gt;&gt;(Alert, Subscribers)
    var joinResultType = doubleTuple.MakeGenericType(new Type[] { alertType, typeof(IEnumerable&lt;AlertSubscription&gt;) });
    ParameterExpression alertTupleParameter = Expression.Parameter(alertType, "Alert");
    ParameterExpression subscribersTupleParameter = Expression.Parameter(typeof(IEnumerable&lt;AlertSubscription&gt;), "Subscribers");
    NewExpression joinResultObject = Expression.New(
      joinResultType.GetConstructor(new Type[] { alertType, typeof(IEnumerable&lt;AlertSubscription&gt;) }),
      alertTupleParameter,
      subscribersTupleParameter);
  
    LambdaExpression resultsSelector = Expression.Lambda(joinResultObject, alertTupleParameter, subscribersTupleParameter);
  
    //Generates:
    //  .GroupJoin(dataContext.AlertSubscriptions,
    //    a =&gt; new { a.AdAccountId, typeof(AdAccount).Name },
    //    s =&gt; new { s.EntityId, s.EntityType },
    //    (Alert, Subscribers) =&gt; new Tuple&lt;Alert, IEnumerable&lt;AlertSubscription&gt;&gt;(Alert, Subscribers))
    IQueryable&lt;AlertSubscription&gt; alertSubscriptions = dataContext.AlertSubscriptions.AsQueryable();
    MethodCallExpression joinExpression = Expression.Call(typeof(Enumerable),
      "GroupJoin",
      new Type[]
      {
        alertType,
        alertSubscriptions.ElementType,
        outerSelector.Body.Type,
        resultsSelector.ReturnType
      },
      unnotifiedAlertsList,
      alertSubscriptions.Expression,
      outerSelector,
      innerSelector,
      resultsSelector);
  
    //Generates: .Where(s =&gt; s.Item2.Any())
    ParameterExpression subscribersParameter = Expression.Parameter(resultsSelector.ReturnType, "s");
    MemberExpression tupleSubscribers = Expression.Property(subscribersParameter, resultsSelector.ReturnType.GetProperty("Item2"));
    MethodCallExpression hasSubscribers = Expression.Call(typeof(Enumerable),
      "Any",
      new Type[] { alertSubscriptions.ElementType },
      tupleSubscribers);
    LambdaExpression whereLambda = Expression.Lambda(hasSubscribers, subscriptionParameter);
    MethodCallExpression whereExpression = Expression.Call(typeof(Enumerable),
      "Where",
      new Type[] { joinResultType },
      joinExpression,
      whereLambda);
  </code></pre>