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; }
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);
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();
The results is:
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();
Then we can run the application to test.
Summary
It's easy to create a lambda expression object based on input, output and its types.
Top comments (0)