Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 898
Omar As'hab Avatar asked Oct 10 '12 07:10

Omar As'hab


2 Answers

You can use Reflection:

list = testList.Where(x => (x.GetType()
              .GetProperty(searchField)
              .GetValue(x) as string).Contains(searchString)    
     );
like image 198
cuongle Avatar answered Oct 06 '22 00:10

cuongle


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);
}
like image 26
Asif Mushtaq Avatar answered Oct 05 '22 23:10

Asif Mushtaq