How to use expression to combine Linq and intersect?

I have code

public static class PredicateExtensions
    {

        public static Expression<Func<T, bool>> True<T>() { return f => true; }
        public static Expression<Func<T, bool>> False<T>() { return f => false; }

        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expression1, Expression<Func<T, bool>> expression2)
        {
            var invokedExpression = Expression.Invoke(expression2, expression1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>(Expression.Or(expression1.Body, invokedExpression), expression1.Parameters);
        }
        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expression1, Expression<Func<T, bool>> expression2)
        {
            var invokedExpression = Expression.Invoke(expression2, expression1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>(Expression.And(expression1.Body, invokedExpression), expression1.Parameters);
        }
    }

      

How can I use this code instead of LINQ Union and Intersect methods?

+3


source to share


1 answer


If you have a union and intersection of a shape:

var union = source.Where(predicate0).Union(source.Where(predicate1));
var inter = source.Where(predicate0).Intersect(source.Where(predicate1));

      

Then union

will matter for which either predicate0

, or predicate1

were true, and inter

will have the values for which both predicate0

and predicate1

are true.

For this reason, the following result will have the same result:

var union = source.Where(predicate0.Or(predicate1));
var inter = source.Where(predicate0.And(predicate1));

      



It depends on the union and intersection components that the two queries create Where

. In such cases:

var union = source1.Where(predicate0).Select(item => item.ID)
  .Union(source2.Where(predicate1).Select(item => item.ID));

      

Then the predicates are probably not of the same type, and there are still other cases where combining predicates will not work as a replacement for union

and Intersect

.

While it is helpful to be able to look at the first examples in both directions, from a single understanding of how predicates, unions, and intersections work.

0


source







All Articles