tags:

views:

73

answers:

3

Hi,

I'm filling a drop-down list using the following:

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

I'm then converting that to a List<String> to populate a drop down list.

I then want to be able to get a set of results based on the user's selection. For example, if they select "First name" from the drop down list and type "Bob" into the text box I want to run a LINQ query where first name = bob.

I'm probably being thick but I can't find a way! Pseudo code would be...

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

Can anybody help? Essentially I have the column name as a String value, and I can't figure out how to tell the LINQ query that that's the column to filter on!

Could do this in ADO.NET with my eyes closed, but determined to use LINQ all the way!!

Thanks in advance.

A: 

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

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 keep building the wheres. The SQL won't be executed as long as none of the calls force the IQueryable to execute.

Robaticus
+1  A: 

David Buchanan has posted a solution for this problem using reflection :

msdn forum

Stephane
Thanks - the perfect starting point. Back to school though for me... :)
LiverpoolsNumber9
A: 

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 the alternate way I would have done this if I didn't feel like learning 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 a class like this for each filter type, and then fill your dropdown with these filters, and when they type info into the filter text, it will execute against the ((IFilter)filterDropDown.SelectedItem).RetreiverFilter(filterTextBox.Text);

Jimmy Hoffa