How to use dropdown value (String) to filter linq results?

I populate the dropdown using the following:

var columnNames = db.Mapping.MappingSource.GetModel(typeof(StaffDirectoryDataContext)) .GetMetaType(typeof(Person)).DataMembers; 

Then I will convert this to List<String> to populate the drop down list.

Then I want to get a result set based on user selection. For example, if they select “Name” from the drop-down list and type “Bob” in the text box, I want to run a LINQ query, where name is name = bob.

I’m probably fat, but I can’t find a way! The pseudo code will be ...

 var q = from x in dc.Persons where x.[selected column name] == [textbox value] select x; 

Can anyone help? Essentially, I have the column name as a String value, and I cannot figure out how to tell the LINQ query that this filter will be filtered!

I could do it in ADO.NET with my eyes closed, but decided to use LINQ all the way!

Thanks in advance.

+4
source share
3 answers

David Buchanan published a solution to this problem using reflection:

msdn forum

+1
source

I'm not sure that you can do this dynamically, but you can do it conditionally. Something like that:

 switch(selected column name) { case "student_no": q = q.where(p=>p.StudentNo == value); break; case "student_id": q = q.where(p=>p.StudentId == value); break; } 

You can iterate through your columns and continue to build schemas. SQL will not be executed until none of the calls force IQueryable to execute.

0
source

I think expression trees are the right way to do this, but I don’t know them very well, so I’m going to give you an alternative way that I would do this if I didn’t want to study the expression tree building ..

 public interface IFilter { IEnumerable RetreiveFilter(string filterValue); } public class FirstNameFilter : IFilter { private const string FILTER_TYPE_NAME = "First Name"; public IEnumerable RetreiveFilter(string filterValue) { return _myData.Where(person => person.FirstName = filtervalue); } public override string ToString() { return FILTER_TYPE_NAME; } } 

Create such a class for each type of filter, and then fill out the drop-down list with these filters, and when they enter information into the filter text, it will be executed with ((IFilter)filterDropDown.SelectedItem).RetreiverFilter(filterTextBox.Text);

0
source

All Articles