首页新闻找找看学习计划

动态构建Lambda表达式的问题

0
[已解决问题] 解决于 2014-05-09 10:19
动态构建Lambda表达式的问题
public class A
{
public int Id
public string Name
public B b
}
public class B
{
public int Id

}
List<A> h=new List<A>();
我想拼接出 这样的 表达式 h.where(p=>p.b.id>9).toList()
请问要什么写?
呗嘞呜的主页 呗嘞呜 | 初学一级 | 园豆:2
提问于:2014-05-08 23:15
< >
分享
最佳答案
0
            var parameter = Expression.Parameter(typeof(A), "a");
            var member = Expression.Field(parameter, "b");
            member = Expression.Field(member, "id");
            var constant = Expression.Constant(9);
            var bin = Expression.GreaterThan(member, constant);
            var lambda = Expression.Lambda<Func<A, bool>>(bin, parameter);
            h.Where(lambda.Compile()).ToList();
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Test
{
    public class A
    {
        public int Id;
        public string Name;
        public B b;
    }
    public class B
    {
        public int Id;

    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        List<A> h = new List<A>(){
            new A(){ b = new B(){ Id = 1}},
            new A(){ b = new B(){ Id = 3}},
            new A(){ b = new B(){ Id = 11}},
            new A(){ b = new B(){ Id = 13}},
            new A(){ b = new B(){ Id = 12}},
            new A(){ b = new B(){ Id = 7}},
            new A(){ b = new B(){ Id = 9}}
        };

        private void Form1_Load(object sender, EventArgs e)
        {
            var parameter = Expression.Parameter(typeof(A), "a");
            var member = Expression.Field(parameter, "b");
            member = Expression.Field(member, "id");
            var constant = Expression.Constant(9);
            var bin = Expression.GreaterThan(member, constant);
            var lambda = Expression.Lambda<Func<A, bool>>(bin, parameter);

            h.Where(lambda.Compile()).ToList().ForEach(n => MessageBox.Show(n.b.Id.ToString()));
        }
    }
}
奖励园豆:5
刘宏玺 | 专家六级 |园豆:14004 | 2014-05-09 09:24

感谢 博客¥  回答,谢谢,问题解决了

呗嘞呜 | 园豆:2 (初学一级) | 2014-05-09 10:20
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册