简体   繁体   中英

Get lambda expression from where clause or IQueryable/IEnumerable

Is there a way to get the expression from known where clause, then pass it to other Where(<expression>) clause?

I'm on .NET Core 3.0 preview with EF Core preview.

Included linq and linq dynamic

public void myFunction ()
{
    var expression = GetAllItems()
                       .Where(x => x.Id == 5 && x.Desc.Contains("foos"))
                       .AwesomeGetExpressioneMagicFunction();
    var res = GenericBeforeSaveValidation(expression);
}

public IQueryable<T> GenericBeforeSaveValidation("delegate/expression" exp)
{
     //some generic stuff before 
     return sourceItems.Where(exp);
}

Just save the lambda in a function variable and reuse it:

public void myFunction ()
{
    Expression<Func<ItemType, bool>> expression = x => x.Id == 5 && x.Desc.Contains("foos");
    var items = GetAllItems()
        .Where(expression)
        .ToList();
    var res = GenericBeforeSaveValidation(expression);
}

public IQueryable<ItemType> GenericBeforeSaveValidation(Expression<Func<ItemType, bool>> exp)
{
     //some generic stuff before 
     return sourceItems.Where(exp);
}

"itemType" is the actual type of your items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM