Dynamic LINQ - ParseLambda

CSharp · Console

/Program.cs

using System;
using System.Linq.Dynamic.Core;
using System.Linq;
using System.Collections.Generic;


// Setup a list of objects to query
var customers = new List<Customer>
{
    new Customer { City = "London", Orders = { "A" }, CompanyName = "Alpha" },
    new Customer { City = "London", Orders = { "A" }, CompanyName = "TestCo" },
    new Customer { City = "Paris", Orders = { "B" }, CompanyName = "Beta" },
}.AsQueryable();

// 1. Create the first dynamic predicate (e1: City = "London")
var e1 = DynamicExpressionParser.ParseLambda<Customer, bool>(
    new ParsingConfig(), true, "City = @0", "London"
);

// 2. Create the second dynamic predicate (e2: CompanyName != "TestCo")
var e2 = DynamicExpressionParser.ParseLambda<Customer, bool>(
    new ParsingConfig(), true, "c => c.CompanyName != \"TestCo\""
);

// 3. Combine them using dynamic invocation in a Where clause:
// @0(it) AND @1(it)
// - @0 and @1 reference the lambda expressions e1 and e2.
// - 'it' represents the current item (Customer) being evaluated.
var filteredCustomers = customers.Where("@0(it) and @1(it)", e1, e2).ToList();

// Output: Only the customer who is in London AND whose CompanyName is NOT "TestCo"
Console.WriteLine($"Found {filteredCustomers.Count} customer(s).");
Console.WriteLine($"Result: {filteredCustomers.First().CompanyName} in {filteredCustomers.First().City}");

public class Customer
{
    public string City { get; set; }
    public string CompanyName { get; set; }
    public List<string> Orders { get; set; } = new List<string>();
}

// Output:
// Found 1 customer(s).
// Result: Alpha in London

;