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;
}
"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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With