5

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.

Omar As'hab
  • 138
  • 5

2 Answers2

3

You can use Reflection:

list = testList.Where(x => (x.GetType()
              .GetProperty(searchField)
              .GetValue(x) as string).Contains(searchString)    
     );
cuongle
  • 74,024
  • 28
  • 151
  • 206
3

You can implement it like the following.

if(searchField == "ID")
{
   testList = testList.Where(x => x.ID == searchString);
}
else if (searchField == "Name")
{
   testList = testList.Where(x => x.Name.Contains(searchString);
}
else if (searchField == "Nationality")
{
   testList = testList.Where(x => x.Nationality.Contains(searchString);
}
Asif Mushtaq
  • 13,010
  • 3
  • 33
  • 42
  • This would work thank you, but the problem is that in the class i have so many attributes to be used, and i have a lot of other classes as well, so i wanted a simple and quick method. – Omar As'hab Oct 10 '12 at 08:03