title: How to sort a List<> that contains derived class objects, by derived class method
body: <p>I have a double problem here.  I need to sort a List&lt;> that I know contains objects of a derived class to the class that the list was declared to contain originally.  AND, I need to sort by the return value from a method in that derived class, which takes a parameter.  Keep in mind that I already know the List contains objects all of the derived class type.</p>
  
  <p>I've created some sample code here to demonstrate the question since the real code cannot be shared publicly.  Note, I have no control over the base conditions here (i.e. the fact that the List&lt;> collection's declared contents are the parent class and that it contains objects of the derived class, which contains a method that takes an argument and returns the values that I need to sort the collection by).  So, I doubt I'd be able to use any suggestion that requires changes there.  What I think I need is a way to specify (cast?) what is really in the List so I can access the method defined there. But I'm open to other thoughts for sure.  Otherwise I'm left with a traditional bubble sort.  Thanks.</p>
  
  <pre><code>public class Component
  {
    public int X;
    public int Y;
  }
  
  public class ComponentList : List&lt;Component&gt;
  {
    // Other members that deal with Components, generically
  }
  
  
  public class Fence : Component
  {
    public int Distance(int FromX, int FromY)
    {
      int returnValue = 0;
      // Caluclate distance...
      return returnValue;
    }
  }
  
  public class Yard : Component
  {
    // Yada yada yada
  }
  
  public class MyCode
  {
    public List&lt;Component&gt; MyFences;
  
    public MyCode(List&lt;Component&gt; Fences, int FromX, int FromY)
    {
      // Sort the fences by their distance from specified X,Y
      Fences.Sort((A as Fence, B as Fence) =&gt; A.Distance(FromX, FromY).CompareTo(B.Distance(FromX, FromY)));
  
      // Or
      List&lt;Fence&gt; sortedFences = MyFences.OrderBy(A =&gt; A.Distance(FromX, FromY)).ToList();
  
      // Or ???
    }
  }
  </code></pre>