Create expression with different types
How can I change if (propType.PropertyType == typeof(string)) and if (propType.PropertyType == typeof(int)) to something more dynamic?
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,
开发者_如何学JAVA Expression.Constant(int.Parse(textBox3.Text))
), param));
}
else
{
throw new NotImplementedException();
}
}
}
dataGridView1.DataSource = lista.ToList();
}
My friend @danielpresser send me a tip on twitter to use Convert.ChangeType and my method changed to this:
lista = lista.Where(Expression.Lambda<Func<Pessoa, bool>>(
Expression.Equal(
propriedade,
Expression.Constant(Convert.ChangeType(textBox3.Text, propType.PropertyType))
), param));
精彩评论