c# - 从列表的自定义列中选择一个元素

标签 c# asp.net class lambda entities

我不能在这里复制我的代码,但是,例如,我有一个像这样的实体:

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

从查询字符串中我得到了 searchField 和 searchString,我将这些值存储在字符串 searchField 和 searchString 中。

我想要一些类似于此功能的东西(我知道这是错误的,但我想要那个功能):

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

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

最佳答案

你可以使用反射:

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

关于c# - 从列表的自定义列中选择一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12814399/

相关文章:

c# - ListView 'SelectionChanged' 事件后聚焦于 TextBox

c# - 我可以利用 ViewState 来消除传递查询字符串的需要吗?

java - 尝试获取具有通用参数的类

javascript - 我可以在索引数据库中存储 javascript 类对象吗?

c# - 'int'不包含'ToList'的定义

c# - 如何在 Windows 应用商店应用程序中使用 GeoPoint API 获取我的当前位置?

c# - Jabber 作为 asp.net 网站的聊天系统

asp.net - 我可以在 apache 服务器上托管 ASP.NET 吗?

javascript - 在导出期间显示更新进度

java - 将父类扭曲为子类