0

How can I create and initialize the following class? Specifically I'm struggling with TSortKey. I thought it would be something like:

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

What I'm trying to do is replace the GetEmployees method arguments in the code below with the QueryParameters object above.

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

I think I'm close but I might also be out in left field.

Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237
Jay Pondy
  • 176
  • 2
  • 11

1 Answers1

1

You're a bit out in left field. Generic parameter's need to be type names (classes, structs, interfaces). You appear to trying to pass a lamdba method, that is not a class, struct, or an interface so it won't work.

What you could do is:

var p = new QueryParameters<Employee, string>();
p.SortSelector = e => e.LastName;
shf301
  • 31,086
  • 2
  • 52
  • 86
  • That did it!! Thank you. I'm just getting my feet wet in trying to adopt a more generic and functional approach to coding. At this point I find the sample code above more difficult to read and comprehend. Am I on the right track? – Jay Pondy May 31 '15 at 06:42