使用不同类型创建表达式

时间:2010-10-22 12:36:01

标签: c# lambda expression

如何将(propType.PropertyType == typeof(string))和if(propType.PropertyType == typeof(int))更改为更动态的内容?

private void button2_Click(object sender, EventArgs e)
        {
            var lista = _pessoas.AsQueryable();

            if (textBox2.Text != "")
            {
                var param = Expression.Parameter(typeof(Pessoa), "x");

                var propriedade = Expression.Property(param, textBox2.Text);

                var propType = typeof(Pessoa).GetProperties().FirstOrDefault(x => x.Name == textBox2.Text);

                if (propType.PropertyType == typeof(string))
                {
                    lista = lista.Where(Expression.Lambda<Func<Pessoa, bool>>(
                        Expression.Equal(
                            propriedade,
                            Expression.Constant(textBox3.Text)
                            ), param));
                }
                else
                {
                    if (propType.PropertyType == typeof(int))
                    {
                        lista = lista.Where(Expression.Lambda<Func<Pessoa, bool>>(
                                Expression.Equal(
                                    propriedade,
                                    Expression.Constant(int.Parse(textBox3.Text))
                                    ), param));
                    }
                    else
                    {
                        throw new NotImplementedException();
                    }
                }
            }

            dataGridView1.DataSource = lista.ToList();
        }

1 个答案:

答案 0 :(得分:1)

我的朋友@danielpresser向我发送tip on twitter以使用Convert.ChangeType,我的方法更改为:

        lista = lista.Where(Expression.Lambda<Func<Pessoa, bool>>(
            Expression.Equal(
                propriedade,
                Expression.Constant(Convert.ChangeType(textBox3.Text, propType.PropertyType))
                ), param));