1

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,
                                    Expression.Constant(int.Parse(textBox3.Text))
                                    ), param));
                    }
                    else
                    {
                        throw new NotImplementedException();
                    }
                }
            }

            dataGridView1.DataSource = lista.ToList();
        }
1
  • I don't think you can. However, you can get rid of the braces around the else and simply use an else if(propType.PropertyType == typeof(int)) Commented Oct 22, 2010 at 12:45

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.