Last active
March 27, 2018 08:16
-
-
Save nzhul/cb94b953de967eac14dd91306083c70d to your computer and use it in GitHub Desktop.
Original article: https://www.strathweb.com/2018/01/easy-way-to-create-a-c-lambda-expression-from-a-string-with-roslyn/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using Microsoft.CodeAnalysis.CSharp.Scripting; | |
using Microsoft.CodeAnalysis.Scripting; | |
namespace CorePlayground | |
{ | |
public class Album | |
{ | |
public int Quantity { get; set; } | |
public string Title { get; set; } | |
public string Artist { get; set; } | |
} | |
public class Program | |
{ | |
/// <summary> | |
/// WARN: Use this on application startup because it is kinda slow operation. | |
/// </summary> | |
/// <param name="args"></param> | |
static void Main(string[] args) | |
{ | |
var albums = new List<Album> | |
{ | |
new Album { Quantity = 10, Artist = "Betontod", Title = "Revolution" }, | |
new Album { Quantity = 50, Artist = "The Dangerous Summer", Title = "The Dangerous Summer" }, | |
new Album { Quantity = 200, Artist = "Depeche Mode", Title = "Spirit" }, | |
}; | |
string discountFilter = "album => album.Quantity > 50"; | |
ScriptOptions options = ScriptOptions.Default.AddReferences(typeof(Album).Assembly); | |
Func<Album, bool> discountFilterExpression = CSharpScript.EvaluateAsync<Func<Album, bool>>(discountFilter, options).Result; | |
IEnumerable<Album> discountedAlbums = albums.Where(discountFilterExpression); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment