如何创建和初始化以下类?具体来说,我正在努力与TSortKey
。我认为它会是这样的:
var p = new QueryParameters<Employees, e => e.LastName>(); // WRONG!!
public class QueryParameters<T, TSortKey> where T : class
{
public int Page { get; set; }
public int PageSize { get; set; }
public string Filter { get; set; }
public Func<T, TSortKey> SortSelector { get; set; }
public bool Ascending { get; set; }
}
我要做的是将上面代码中的GetEmployees
方法参数替换为上面的QueryParameters
对象。
public QueryResults<Employees> GetEmployees<TSortKey>(int page, int pageSize, string filter, Func<Employees, TSortKey> sortSelector, bool asc)
{
IEnumerable<Employees> query = Employees;
if (filter != "*")
{
query = query.Where (e => e.LastName.StartsWith(filter));
}
if (sortSelector != null)
{
query = asc ? query.OrderBy(sortSelector) : query.OrderByDescending(sortSelector);
}
var results = new QueryResults<Employees>
{
TotalItems = query.Count(),
Items = query.Skip((page - 1) * pageSize).Take(pageSize)
};
return results;
}
public class QueryResults<T> where T : class {
public IEnumerable<T> Items { get; set; }
public int TotalItems { get; set; }
}
我觉得我很接近,但我可能也会离开。
答案 0 :(得分:1)
你在左场有点出局。通用参数需要是类型名称(类,结构,接口)。您似乎尝试传递lamdba方法,该方法不是类,结构或接口,因此它不起作用。
你能做的是:
var p = new QueryParameters<Employee, string>();
p.SortSelector = e => e.LastName;