本文介绍了评估存储在字符串参数中的lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请检查以下代码

Please check below code

List<Emp> empD = new List<Emp> { new Emp { Name = "a", age = 1 }, new Emp { Name = "b", age = 2 } };
            var test = "empD.Where(x=>x.age ==1 )";
            var param1 = Expression.Parameter(typeof(Emp), "test");
            var lambda = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { param1 }, typeof(Emp), test);
            var rest = lambda.Compile();



这里我试图评估lambda表达式但是输入将在字符串参数中给出,它存储表达式。我如何评估以获取实体列表。



预先感谢

Jayanth


Here i am trying to evaluate lambda expression but input will be given in string param , which stores expression.How can i evaluate to get list of entity.

Thanks in Advance
Jayanth

推荐答案

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinqDelegate
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Emp> empD = new List<Emp> { new Emp("a", 1),
                                    new Emp("b", 2),
                                    new Emp("c", 1),
                                    new Emp("d", 4) };

            Func<Emp, int, bool> predicate = (e, i) => e.Age==1;

            var qry = empD.Where(predicate).Select(x => x);
            foreach (var e in qry)
                Console.WriteLine("{0} = {1}", e.Name, e.Age);

            Console.ReadKey();

        }

        class Emp
        {
            private string sName = String.Empty;
            private int iAge = 0;

            public Emp(string _Name, int _Age)
            {
                sName = _Name;
                iAge = _Age;
            }

            public string Name
            {
                get { return sName; }
                set { sName = value; }
            }

            public int Age
            {
                get { return iAge; }
                set { iAge = value; }
            }
        }
    }
}



结果:


Result:

a = 1
c = 1


这篇关于评估存储在字符串参数中的lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 13:13