c# - 可以创建 key 未知的通用搜索方法

标签 c# linq generics

是否可以创建一个 key 未知的通用搜索方法?例如,列表的键将传递给参数,它执行类似的搜索并返回过滤后的列表。

代码应该是这样的:

public List<T> LikeSearch<T>(List<T> AllData,T key, string searchString)
{
  List<T> _list = new List<T>();
  //Perform the search on AllData based on searchString passed on the key   
  //given
 return _list;
}

用途如下:

示例 1

List<Users> _users = LikeSearch<Users>(AllUsers,'Name','sam');

其中 AllUsers 是 100 个 users 的列表。

示例 2

List<Customers> _cust = LikeSearch<Customers>(AllCustomers,'City','London');

其中 AllCustomers 是 100 个 Customers 的列表。

请建议

最佳答案

假设 key 总是引用由任何类型 T 实现的公共(public)属性,您可以执行以下操作:

public static List<T> LikeSearch<T>(this List<T> data, string key, string searchString)
{
    var property = typeof(T).GetProperty(key, BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance);

    if (property == null)
        throw new ArgumentException($"'{typeof(T).Name}' does not implement a public get property named '{key}'.");

    //Equals
    return data.Where(d => property.GetValue(d).Equals(searchString)).ToList();

    //Contains:
    return data.Where(d => ((string)property.GetValue(d)).Contains(searchString)).ToList();
}

关于c# - 可以创建 key 未知的通用搜索方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39120429/

相关文章:

c# - 在 Asp.net MVC 和 Entity Framework 中分页时如何应用过滤器?

c# - WPF 4.5 绑定(bind)到静态属性

c# - 有关如何教程(WPF/Entity Framework/ObservableCollections)的问题

c# - 为什么 C# 中的这种隐式类型转换会失败?

java - 可以将泛型添加到 Java 中非泛型接口(interface)的实现中吗?

c# - 结合RFID读写器在arduino中接收USB串口数据

c# - SQL : Select Distinct rows by all columns but omit one column (say ID column)

c# - linq min 问题/bug

c# - LINQ 2 SQL 嵌套表插入错误毫无意义

generics - 如何为具有类型参数的类编写辅助构造函数?