[Fork] Filtering by list of compound keys -- first try

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");
        Expression predicate = null;

        foreach (var key in keysToFind)
        {
            // create the predicate for the current key
            // === DOES NOT YET WORK ===
            var keyPredicate = Expression.AndAlso(
                Expression.Equal(key1Expression, Expression.Constant(key.Key1)),
                Expression.Equal(key2Expression, Expression.Constant(key.Key2)));

            // OR it with the previous key predicates
            if (predicate == null)
            {
                predicate = keyPredicate;
            }
            else
            {
                predicate = Expression.OrElse(predicate, keyPredicate);
            }
        }

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

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

        return query;
    }
}
;