Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic build lambda expressions

Tags:

c#

lambda

So, I started to build a small test application to test lambda expressions. I found several examples here and elsewhere but I just don't get them.

Can anybody explain my how to build an expression by using textboxes or any other variables?

My Test List

List<People> lPeople = new List<People> 
{
    new People { Name= "Jean", LastName = "Borrow", Age= 21 } ,
    new People { Name= "Dean", LastName = "Torrow", Age= 20 }
};

Working lambda Expression

IEnumerable<People> result = lPeople.Where(p => p.Age < 21);
dgv_1.DataSource = result.ToList();
dgv_1.Update();

How can I build the expressions dynamically?

Something like lPeople.Where(p => p.LastName == Textbox.Text); (which of course doesn't work)

Thanks!

Edit: Added some code to the solution below

Int32 iAge;
Boolean bSuc = Int32.TryParse(tb_filter_age.Text, out iAge);
if (!bSuc)
{
    iAge = 0;
}
like image 717
Henrik P. Hessel Avatar asked Dec 04 '22 15:12

Henrik P. Hessel


2 Answers

"which of course doesn't work"

What happens when you try it? By the look of it, that's the kind of thing I do all the time.

To switch operations based on a ComboBox specifying the operator:

int age = int.Parse(textBoxAge.Text);

IEnumerable<People> result;
if (comboBoxOperator.Text == "=")
    result = lPeople.Where(p => p.Age == age);
else if (comboBoxOperator.Text == "<")
    result = lPeople.Where(p => p.Age < age);
else
    result = lPeople.Where(p => p.Age > age);

dgv_1.DataSource = result.ToList();
dgv_1.Update();

The code that converts the age string into an int will throw if the user enters something that can't be converted. Look up TryParse to avoid exceptions.

like image 120
Daniel Earwicker Avatar answered Dec 06 '22 05:12

Daniel Earwicker


Try the Predicate Builder at http://www.albahari.com/nutshell/predicatebuilder.aspx

I used it to make an advanced search where the user could keep adding optional search criteria.

like image 30
Sudhir Jonathan Avatar answered Dec 06 '22 05:12

Sudhir Jonathan