Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Converting Lambda Expression Function to Descriptive String

Tags:

c#

lambda

I have quite an unnecessary dilemma. I'm lazily looking for a function that would convert a lamda expression into a string. It bothers me that I'm typing in this cache key every time but I don't really want to take the time to create it.

I want to use it for a cache function I created:

Where if I wanted to get a name for a person without calling the function every time.

public static string GetPersonName(int id)
{
    return Repository.PersonProvider.Cached(x => x.GetById(id)).Name;
}

The GetExpressionDescription would return "PersonProvider.GetById(int 10)"

I figure this is possible but I wonder if anyone has already built this or has seen it somewhere.

public static R Cached<T, R>(this T obj, Expression<Func<T, R>> function, double hours = 24)
{
    var expressionDescription = GetExpressionDescription(function); 
    return Cached(function, expressionDescription, hours); 
}

public static R Cached<T, R>(this T obj, Expression<Func<T, R>> function, string cacheName, double hours = 24)
{
    var context = HttpContext.Current;
    if (context == null)
        return function.Compile().Invoke(obj);

    R results = default(R);
    try { results = (R)context.Cache[cacheName]; }
    catch { }
    if (results == null)
    {
        results = function.Compile().Invoke(obj);
        if (results != null)
        {
            context.Cache.Add(cacheName, results, null, DateTime.Now.AddHours(hours),
                              Cache.NoSlidingExpiration,
                              CacheItemPriority.Default, null);
        }
    }
    return results;
}
like image 665
Kyle Avatar asked Nov 21 '11 16:11

Kyle


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.


2 Answers

You can simply get a string representation of an Expression<> with .ToString():

using System;
using System.Linq.Expressions;

public class Program
{
    public static void Main()
    {
        Test(s => s.StartsWith("A"));
    }

    static void Test(Expression<Func<string,bool>> expr)
    {
        Console.WriteLine(expr.ToString());
        Console.ReadKey();
    }
}

Prints:

s => s.StartsWith("A")

See: https://dotnetfiddle.net/CJwAE5

But of course it will not yield you the caller and the values of variables, just the expression itself.

like image 184
Olivier Jacot-Descombes Avatar answered Nov 03 '22 22:11

Olivier Jacot-Descombes


Maybe you should try DynamicExpresso. I used that library to develop a lightweight business-rules engine.

https://github.com/davideicardi/DynamicExpresso

like image 2
Rénald Avatar answered Nov 03 '22 20:11

Rénald