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