Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
Hi EveryBody, i'm trying Too use a listBox for Select the Search,
but i can't use the string si in LINQ, i don't know how use it,
i made this code, but don't know how use the si.
C#
var db = new DataClasses1DataContext();
int selectedIndex = listBox1.SelectedIndex;
string si = "";
if (selectedIndex == 0) si = "id" ;
if (selectedIndex == 1) si = "name";
if (selectedIndex == 2) si = "sex";
if (selectedIndex == 3) si = "address";
if (selectedIndex == 4) si = "phone";
if (selectedIndex == 5) si = "web";
var qsearch = db.users.Where(c => c.[i want use si in this place].Contains(textBox7.Text));
dataGridView1.DataSource = qsearch;
Posted
Updated 29-Jan-15 9:59am
v2

Good one!

You need to build dynamic expression. Something like this:
C#
var parameter = Expression.Parameter(typeof(user), "p");
var property = Expression.Property(parameter, si);
var check = Expression.Call(property, typeof(String).GetMethod("Contains"), Expression.Constant(textBox7.Text));
var query = db.users;
var predicate = Expression.Lambda<Func<user, bool>>(check, parameter);
var result = query.Where(predicate);

To build a more complex query, use the approaches from here: http://blog.micic.ch/net/entity-framework-and-expression-queries[^]
 
Share this answer
 
Comments
George Swan 29-Jan-15 18:18pm    
I think you may have forgotten to compile the Expression.
var predicate = Expression.Lambda<Func<user, bool>>(check, parameter).Compile();
Zoltán Zörgő 29-Jan-15 18:19pm    
It is working even without.
George Swan 29-Jan-15 18:34pm    
It's a great solution. I'd have declared an array of delegates and indexed into the required one in the Where statement.
var TestFunctions = new Func<users, bool>[6];
TestFunctions[0] = c=>c.id.Contains(textBox7.Text);
TestFunctions[1] = c=>c.name.Contains(textBox7.Text);
//........................
var qsearch = db.users.Where(testFunctions[selectedIndex]);
Maciej Los 8-Feb-15 12:39pm    
It's worth to post as an answer.
Maciej Los 8-Feb-15 12:40pm    
+5!
with this code we can solve this proble, use switch for solve
C#
var db = new DataClasses1DataContext();
int selectedIndex = listBox1.SelectedIndex;
switch (selectedIndex)
{
   case 0:
     dataGridView1.DataSource = db.users.Where(c => c.id.ToString().Contains(...));
     break;
   ....
 }
 
Share this answer
 
C#
string searchText = textBox7.Text;
var qsearch = db.users.Where(c => c.id.ToString().Contains(searchText) || c.name).Contains(searchText) || c.sex.ToString.Contains(searchText) ||
c.address.Contains(searchText) || c.phone.ToString().Contains(searchText) ||
c.web.ToString().Contains(searchText));
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900