Search code examples
c#linqlambdalinq-to-sql

How to make linq expression with multiple parameters


I'm trying to write a reusable linq expression that I'm passing multiple parameters into:

private System.Linq.Expressions.Expression<Func<FeeDetail, FeeDetail, bool>> IsPrevFeeDetail
   {
       get
       {
           return (feeLevelDetail, currentFeeLevelDetail) =>
           feeLevelDetail.ToDt < currentFeeLevelDetail.FromDt);
       }
   }

But every example of an expression I've seen only takes one parameter (the Entity type that you are querying against).

Is there any way to do this out of the box?


Solution

  • Your question at the time of my answer simply asks if Expressions with multiple parameters is possible. They can be used, and are.

    .Join and .GroupJoin both have, as a last parameter, an expression parameter that takes types deriving from each side of the join and return a single entity and return a single type.

    tableA.Join(tableB, e => e.Id, e => e.TableAId, (a, b) => new {
        IsPrevFee = a.ToDt < b.FromDt,
        AEntry = a,
        BEntry = b
    }).Where(e => e.IsPrevFee);
    

    However, judging from the example in your question you seem to want to use it in a Where. That doesn't work because any of the Linq query functions give a collection of a single type as the return. You've seen above I've essentially converted the joining of the 2 entities into a single type of output. I've used an anonymous type but it may be helpful to note that this can also be a concrete type which you can then put in a reusable expression for the join, and then you've got a single-input expression you can pass to a Where clause.

    EDIT for comments:

    You should be able to create an Expression<Func<MyEntity, bool>> by closing around another argument. I'm doing this on the fly so ignore any trivial syntax errors but an example would be something like this:

    Expression<Func<MyEntity, bool>> GetMyWhereClause(int statusId)
    {
        return myEntity => myEntity.StatusId == statusId;
    }
    

    Usage:

    var MyWhereClause = GetMyWhereClause(5);
    var result = db.MyEntities.Where(MyWhereClause);
    

    I'm not certain but I don't believe this will work for non-primitives as LINQ-to-SQL may not be able to resolve the resulting expression.