C# 从列表中的自定义列中选择元素

C# 从列表中的自定义列中选择元素,c#,asp.net,class,lambda,entities,C#,Asp.net,Class,Lambda,Entities,我正在尝试使用webservice for JQgrid在具有自定义列名的列表中搜索自定义元素,但是我没有主意,我希望在这方面能得到任何帮助 我无法在此处复制代码,但例如,我有一个实体,如: public class Test { public int ID {get; set;} public string Name {get; set;} public string Nationality {get; set;} } 我创建了一个函数来返回这个类的列表: publi

我正在尝试使用webservice for JQgrid在具有自定义列名的列表中搜索自定义元素,但是我没有主意,我希望在这方面能得到任何帮助

我无法在此处复制代码,但例如,我有一个实体,如:

public class Test
{
    public int ID {get; set;}
    public string Name {get; set;}
    public string Nationality {get; set;}
}
我创建了一个函数来返回这个类的列表:

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;
}

我获取列表或任何东西都没有问题,但我只想要类似的东西。

您可以使用
反射

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

您可以像下面这样实现它

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);
}

谢谢,但问题是在这个类中我有很多属性要使用,我还有很多其他类,所以我想要一个简单快速的方法。谢谢你的回答,但是它说.GetValue()没有一个重载方法需要一个参数。@OmarAs'hab:如果你使用.Net 4.0,你可以使用
GetValue(x,null)
非常感谢您,它工作得很好,但我不得不将它从as string改为.ToString()。
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);
}