logo
down
shadow

How can I do a Func<object[],Expression<Func<T,bool>>> dynamic?


How can I do a Func<object[],Expression<Func<T,bool>>> dynamic?

Content Index :

How can I do a Func<object[],Expression<Func<T,bool>>> dynamic?
Tag : chash , By : kiirpi
Date : November 24 2020, 05:47 AM


Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Convert Expression<Func<TInterface, bool>> to Expression<Func<TImplementation, bool>>


Tag : linq , By : B3CFT
Date : March 29 2020, 07:55 AM
Does that help AFAIK The BCL has very limited support for working with Expressions. I'm afraid that you're going to have to rewrite the expression yourself to change the method parameter type.
It's not hard, but not easy either. Basically, you will clone every node of the Expression (it's a tree) but set the root node's data type to your Func.
public static Expression<Func<TOut, bool>> CastParam<TIn, TOut>(this Expression<Func<TIn, bool>> inExpr) {
    if (inExpr.NodeType == ExpressionType.Lambda &&
        inExpr.Parameters.Count > 0) {

        var inP = inExpr.Parameters[0];
        var outP = Expression.Parameter(typeof(TOut), inP.Name);

        var outBody = inExpr.Body.ConvertAll(
            expr => (expr is ParameterExpression) ? outP : expr);                           
        return Expression.Lambda<Func<TOut,bool>>(
            outBody,
            new ParameterExpression[] { outP });
    }
    else {
        throw new NotSupportedException();
    }
}
class TInterface { public int IntVal; }
class TImplementation : TInterface { public int ImplVal; }

void Run ()
{
    Expression<Func<TInterface, bool>> intExpr = (i => i.IntVal == 42);
    Expression<Func<TImplementation, bool>> implExpr = intExpr.CastParam<TInterface, TImplementation> ();

    Console.WriteLine ("{0} --> {1}", intExpr, implExpr);

    var c = implExpr.Compile ();

    Console.WriteLine (c.Invoke (new TImplementation { IntVal = 41, ImplVal = 42 }));
    Console.WriteLine (c.Invoke (new TImplementation { IntVal = 42, ImplVal = 41 }));
}
False
True
public static Expression Rewrite(this Expression exp, Func<Expression, Expression> c) {
    Expression clone = null;
    switch (exp.NodeType) {
        case ExpressionType.Equal: {
            var x = exp as BinaryExpression;
            clone = Expression.Equal(Rewrite(x.Left,c), Rewrite(x.Right,c), x.IsLiftedToNull, x.Method);
            } break;
        case ExpressionType.MemberAccess: {
            var x = exp as MemberExpression;
            clone = Expression.MakeMemberAccess(Rewrite(x.Expression,c), x.Member);
            } break;
        case ExpressionType.Constant: {
            var x = exp as ConstantExpression;
            clone = Expression.Constant(x.Value);
            } break;
        case ExpressionType.Parameter: {
            var x = exp as ParameterExpression;
            clone = Expression.Parameter(x.Type, x.Name);
            } break;
        default:
            throw new NotImplementedException(exp.NodeType.ToString());
    }
    return c(clone);
}

Can I use Expression<Func<T, bool>> and reliably see which properties are referenced in the Func<T, bool&


Tag : chash , By : Franky
Date : March 29 2020, 07:55 AM
may help you . Yes, you'll be able to see everything directly referenced. Of course, if someone passes
x => ComputeAge(x) > 18

How do I convert Expression<Func<T, object>> to Expression<Func<T, bool>>?


Tag : chash , By : itsmegb
Date : March 29 2020, 07:55 AM
I wish this help you Assuming that fieldExpression is something like (T e) => e.Field I concluded that you want find in DB record with same value in Field column.
Try this:
foreach (T inputRecord in input)
{
    object fieldObject = fieldDelegate.Invoke(inputRecord);

    ParameterExpression p = fieldExpression.Parameters.First();
    // Equivalent to x => x.Field == fieldObject
    Expression<Func<T, bool>> predicate = Expression.Lambda<Func<T, bool>>(
        // input.Field == fieldObject
        Expression.Equal(
            // input.Field
            fieldExpression.Body,
            // constant from fieldObject
            Expression.Constant(fieldObject)
        ),
        new []{ p }
    );

    T dataRecord = dbSet.SingleOrDefault(predicate);

    if (dataRecord != null)
    {
        inputRecord.CreatedOn = dataRecord.CreatedOn;
    }
}

C# Member expression Func<T,object> to a Func<T,bool> MethodBinaryExpression


Tag : chash , By : Deepak Poondi
Date : March 29 2020, 07:55 AM
around this issue Is it possible to convert a member epxression together with an object to a method binary expression in c#? , You can create just new expression
model=>model.property == object.property

public static void SaveBy<T, TProp>(this IDbConnection db, T obj, Expression<Func<T, TProp>> exp) where T : new()
{
    var memberExp = (MemberExpression)exp.Body;
    var objPropExp = Expression.PropertyOrField(Expression.Constant(obj), memberExp.Member.Name);
    var equalExp = Expression.Equal(exp.Body, objPropExp);
    var exp2 = Expression.Lambda<Func<T, bool>>(equalExp, exp.Parameters);
    //exp2 = {model => (model.prop == value(object).prop)}

    if (db.Update(obj, exp2) <= 0)
    {
        db.Insert(obj);
    }
}

How to convert Linq Expression<Func<object,object,bool>> to Expression<Func<T1,T2,bool>>


Tag : chash , By : quicky
Date : September 25 2020, 07:00 PM
I hope this helps you . I am trying to store all associations/joins for an ORM in a list of , Here is how you can do it:
public class OrmJoin
{
    // ...

    public Expression AsTyped()
    {
        var parameters = new[] { Type1, Type2 }
            .Select(Expression.Parameter)
            .ToArray();
        var castedParameters = parameters
            .Select(x => Expression.Convert(x, typeof(object)))
            .ToArray();
        var invocation = Expression.Invoke(Predicate, castedParameters);

        return Expression.Lambda(invocation, parameters);
    }
    public Expression<Func<T1, T2, bool>> AsTyped<T1, T2>() => (Expression<Func<T1, T2, bool>>)AsTyped();
}
void Main()
{
    var test = new OrmJoin { Type1 = typeof(string), Type2 = typeof(int), Predicate = (a,b) => Test(a,b) };
    var compiled = test.AsTyped<string, int>().Compile();

    Console.WriteLine(compiled.Invoke("asd", 312));
}
bool Test(object a, object b)
{
    Console.WriteLine(a);
    Console.WriteLine(b);
    return true;
}
Related Posts Related QUESTIONS :
  • Absolute path back to web-relative path
  • How can we generate getters and setters in Visual Studio?
  • Bringing Window to the Front in C# using Win32 API
  • Possible to "spin off" several GUI threads? (Not halting the system at Application.Run)
  • Reading a C/C++ data structure in C# from a byte array
  • How should I translate from screen space coordinates to image space coordinates in a WinForms PictureBox?
  • Setting Objects to Null/Nothing after use in .NET
  • Converting ARBG to RGB with alpha blending
  • Is it better to create Model classes or stick with generic database utility class?
  • Passing enum type to Converter with integer value
  • Pool of objects with objects that are already on the scene in advance
  • StatusBar text fade-out when binding using Caliburn.Micro
  • Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException
  • How to get record form a different table based on a value from first table with linq expression?
  • Show data in Grid from returned model
  • Using Attributes to Override Data Model Conventions
  • Basic OOP console calculator, result Error
  • Compositon and Repository pattern
  • Multiple using statements with if condition
  • How do i increase a number by 1 in every line that contain the number 1
  • Add binding to elements that are created in codebehind
  • How to add a column in an existing AspNetUsers table
  • Order a list of elements with another list of doubles
  • How to setup a NuGet package to copy content files to output build directory?
  • In SignalR Core using ChannelWriter: Do I need to call TryComplete twice if there's an exception?
  • C# GetProcessesByName: issue with colon
  • c# wpf | create complex object with user-defined name to Serialize into JSON
  • How can I get a instance of a generic list with reflection?
  • WPF XAML - Design time and visibility of textbox
  • EF Core and MySql query is too slow
  • Getting Registered App Display Name from an App Id
  • How to get all variables from a string
  • Delete entity with all childs connected
  • Azure Build agent cant´t find class library referance
  • Initialize Nested Dictionaries in c#
  • .Net Core Binding
  • Generic event test method, preventing code duplication
  • How do I keep the ellipses in the center when the screen is resized
  • How to require a property using JsonSchema.NET?
  • C# XDocument Element/Elements returns null
  • Autofac keyed service with IEnumerable relationship type
  • Installing EntityFramework via NuGet manager
  • Always Check if there is Internet Connection Xamarin forms
  • WCF OneWay service slows down when aspNetCompatibilityEnabled is set to false
  • Can we use JsonRequestBehavior.AllowGet with [HttpPost] attribute?
  • How to customize the Setup wizard with custom forms in Visual Studio setup project
  • C# ASP.NET - Use method from another class to create labels
  • C# List IList or IEnumerable as argument
  • Parsing File with C# And Replace method
  • Losing special unicode characters in encryption (C#)
  • Getting stored procedure returned value instead of row affected
  • How can I construct HTML using NameValuePair in android?
  • Loading a pop up page in ASP.net through a js file
  • How to pass alert or notification message from controller to View?
  • C# to pause, turn on ssas server, backup cube.... how to?
  • How to execute DataTable.Select() for a column of custom class type for a particular element in that C#
  • how to connect mysql8.0 with C#
  • Passing incorrect values into MultiValueConverter by MultiBinding
  • Can i use IEnumerator as Update func?
  • How to convert API Json response to C# Array?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com