Search code examples
c#asp.netclasslambdaentities

select an element from a custom column from a list


I am trying to implement Searching for a custom element in a list with a custom column name using a webservice for JQgrid, but I am out of ideas I would appreciate any help on this.

I can't copy my code here but, for example, I have an entity like:

public class Test
{
    public int ID {get; set;}
    public string Name {get; set;}
    public string Nationality {get; set;}
}

and I created a function to return a list of this class:

public static List <Test> getList()
{
    List<Test> testList = new List<Test>();
    Test testList1 = new Test();

    testList1.ID = 123;
    testList1.Name = "asd";
    testList1.Nationality = "qwe";

    testList.Add(testList1);
    return testList;
}

and from the querystring I get the searchField and searchString, I have stored these values in strings searchField and searchString.

I want something to work similar to this function (I know its wrong but I want that functionality):

list=testList.Where(x=>x.searchField.Contains(searchString));

I have no problem with getting the list or anything but I just want something similar to this.


Solution

  • You can use Reflection:

    list = testList.Where(x => (x.GetType()
                  .GetProperty(searchField)
                  .GetValue(x) as string).Contains(searchString)    
         );