我想采用下面显示的ResultSet类并对其进行修改,使其可以是通用的。如您所见,它只接受产品列表,但我希望它采用List-OneOfMyModels>或List-T>为了我的控制器中的代码重用性。
public class ResultSet
{
public List<Product> GetResult(string search, string sortOrder, int start, int length, List<Product> dtResult, List<string> columnFilters)
{
return FilterResult(search, dtResult, columnFilters).SortBy(sortOrder).Skip(start).Take(length).ToList();
}
public int Count(string search, List<Product> dtResult, List<string> columnFilters)
{
return FilterResult(search, dtResult, columnFilters).Count();
}
private IQueryable<Product> FilterResult(string search, List<Product> dtResult, List<string> columnFilters)
{
IQueryable<Product> results = dtResult.AsQueryable();
results = results.Where(p => (search == null || (p.Name != null && p.Name.ToLower().Contains(search.ToLower()) || p.PublicDisplayNo != null && p.PublicDisplayNo.ToLower().Contains(search.ToLower())))
);
return results;
}
}
在我的控制器中,我这样调用方法:
public JsonResult DataHandler(DTParameters param)
{
try
{
var dtsource = _context.Products.ToList();
List<String> columnSearch = new List<string>();
foreach (var col in param.Columns)
{
columnSearch.Add(col.Search.Value);
}
List<Product> data = new ResultSet().GetResult(param.Search.Value, param.SortOrder, param.Start, param.Length, dtsource, columnSearch);
int count = new ResultSet().Count(param.Search.Value, dtsource, columnSearch);
DTResult<Product> result = new DTResult<Product>
{
draw = param.Draw,
data = data,
recordsFiltered = count,
recordsTotal = count
};
return Json(result);
}
catch (Exception ex)
{
return Json(new { error = ex.Message });
}
}
答案 0 :(得分:0)
答案 1 :(得分:0)
你必须使整个泛型像public class ResultSet<T>
一样,或者让类中的方法具有泛型输入和返回类型,如public List<T> GetResult(params)
。
但是这在过滤器结果方法中引入了一个新问题,该方法使用实际的Products
类来按其属性执行搜索和过滤。使用Reflections in c#, System.Reflection
查找泛型类的类属性值。