I have many collections for many types I want to sort each collection by different properties. For example IEnumerable<Employee> will be sorted by Name and Age properties,and IEnumerable<Department> will be sorted by NumberOfEmployees and DepartmentName properties. I use PaginatedList to paginating the collection after sorting it.
public class PaginatedList<T> : List<T>
{
public PaginatedList(IEnumerable<T> source, Int32 pageIndex, Int32 pageSize , Func<T,Object> orderBy)
{
this.AddRange(source.OrderBy(orderBy).Skip((PageIndex - 1) * PageSize).Take(PageSize));
}
}
Note the 4th parameter which is the sorting delegate that will be passed to OrderBy extension method.
I am using a generic method to generate this 4th element
public Func<T, Object> SortingFactory<T>(String sortby)
{
switch (typeof(T).ToString())
{
case "Employee":
switch(sortby)
{
case "Name":
return new Func<Employee,String>(delegate(Employee e) { return e.Name; });
break;
case "Age":
return new Func<Employee,Int32>(delegate(Employee e) { return e.Age; });
break;
}
break;
case "Department":
switch(sortby)
{
case "NumberOfEmployees":
return new Func<Department,Int32>(delegate(Department d) { return d.NumberOfEmployees; });
break;
case "DepartmentName":
return new Func<Department,String>(delegate(Department d) { return d.DepartmentName; });
break;
}
break;
}
}
but it gives me a compilation ErrorCannot implicitly convert type 'System.Func<Employee,String>' to 'System.Func<T,object>'
I also tried to decalre the output as Func<Object,Object> but I got the same error.
What is the fault I made and how do such method.
Say I understood well
And if I misunderstood, I think the simple usage of GetSortExpression method can help you to avoid your error