How to Convert Predicate to String and String To Predicate

c# c#-4.0 expression-trees lambda linq

Question

I work on a special project that have to convert Predicates (or Expressions) to string and store on the database and retrieve it and convert it to Predicates and evaluate it because I want to change it in run-time. Please help me to imeplement ConvertStringToPredicate and ConvertStringToPredicate methods.

public class Program
{
    static void Main(string[] args)
    {
        string predicateStr = GetPredicateFromDb(100);

        Predicate<Account> predicate = ConvertStringToPredicate(predicateStr);

        Account account = new Account();

        var status = account.Evaluate(predicate);

        //...
    }

    public static string GetPredicateFromDb(int id)
    {
        //Get Predicate String From Database
        //...
    }

    public static Predicate<Account> ConvertStringToPredicate(string predicate)
    {
        //???
    }

    public static string ConvertStringToPredicate(Predicate<Account> predicate)
    {
        //???
    }
}

public class Account
{
    public decimal Balance { get; set; }

    public bool Evaluate(Predicate<Account> matchingCriteria)
    {
        //Evaluate Predicate
        //...
    }  
}

Popular Answer

There are several libraries for expression trees serialization:

  1. metalinq
  2. expression tree serializer
  3. serialize linq


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why