DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

3

C#: Pass Lambda Expression to Select LINQ at Runtime

In the previous article, I explain how to pass the lambda string to Where clause. In this article, I do pass it to the Select extension method.

Create Classes

I used List<string> before, but let's create the class to test several different scenario.



public class MyClass
public class MyClass
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public int Age { get; set; }
    public string Country { get; set; } = string.Empty;
}


Enter fullscreen mode Exit fullscreen mode

Select LINQ for string

The Select method takes Func<TSource, TResult> delegate. I create List<MyClass> as an input, so the TSource is MyClass this time.

Then how about TResult? It's depends if I want to select a string property of an int property.



ParameterExpression param = Expression.Parameter(typeof(MyClass), "x");
Expression expression = new ExpressionParser(
    new ParameterExpression[] { param },
    "x.name", 
    null, 
    new ParsingConfig())
    .Parse(typeof(string));

Expression<Func<MyClass, string>> lambda = 
    Expression.Lambda<Func<MyClass, string>>(expression, param);


Enter fullscreen mode Exit fullscreen mode

The input parameter is MyClass and I name it as x. Then the query is x.name to return name. Of course, the return type is string type.

Let's create a list and try the code.



List<MyClass> inputs = new() 
{
    new () { Id = 1, Name = "1" },
    new () { Id = 2, Name = "2" }
};

List<string> result = inputs.AsQueryable().Select(lambda).ToList();


Enter fullscreen mode Exit fullscreen mode

The results is:

Image description

Select LINQ for object

If we don't know which property to select yet, we can specify object.



string query = Console.ReadLine();

ParameterExpression param = Expression.Parameter(typeof(MyClass), "x");
Expression expression = new ExpressionParser(
    new ParameterExpression[] { param },
    query, 
    null, 
    new ParsingConfig())
    .Parse(typeof(object));

Expression<Func<MyClass, object>> lambda = 
    Expression.Lambda<Func<MyClass, object>>(expression, param);

//List<string> inputs = new() { "1", "2" };
//var result = inputs.AsQueryable().Where(lambda).ToList();


List<MyClass> inputs = new() 
{
    new () { Id = 1, Name = "1" },
    new () { Id = 2, Name = "2" }
};

List<object> result = inputs.AsQueryable().Select(lambda).ToList();


Enter fullscreen mode Exit fullscreen mode

Then we can run the application to test.

Image description

Summary

It's easy to create a lambda expression object based on input, output and its types.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay