Filtering by list of compound keys -- invoking the key expressions

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using FluentAssertions;

class Program
{
    static void Main()
    {
        var listOfItems = new List<(string Key1, int Key2, string Value)>
            {
                ("foo", 1, "A"),
                ("foo", 2, "B"),
                ("bar", 1, "C"),
                ("bar", 2, "D"),
            };

        var keysToFind = new[]{ ("foo", 1), ("bar", 2) };

        var foundItems = listOfItems.AsQueryable()
            .WhereCompositeKeyContainedIn(
                i => i.Key1,
                i => i.Key2,
                keysToFind)
            .ToList();

        foundItems.Should().BeEquivalentTo(("foo", 1, "A"), ("bar", 2, "D"));
    }
}

public static class MyExpressions
{
    public static IQueryable<TEntity> WhereCompositeKeyContainedIn<TEntity, TKey1, TKey2>(
        this IQueryable<TEntity> query,
        Expression<Func<TEntity, TKey1>> key1Expression,
        Expression<Func<TEntity, TKey2>> key2Expression,
        IEnumerable<(TKey1 Key1, TKey2 Key2)> keysToFind)
    {
        var parameter = Expression.Parameter(typeof(TEntity), "i");

        var predicate = keysToFind
            // create the predicates for the keys
            .Select(key =>
                Expression.AndAlso(
                    Expression.Equal(
                        Expression.Invoke(key1Expression, parameter),
                        Expression.Constant(key.Key1)),
                    Expression.Equal(
                        Expression.Invoke(key2Expression, parameter),
                        Expression.Constant(key.Key2))))
            // aggregate them together with OR
            .Aggregate(Expression.OrElse);

        // create the lambda
        var lambda = Expression.Lambda<Func<TEntity, bool>>(predicate, parameter);

        // apply the lambda
        query = query.Where(lambda);

        return query;
    }
}
;