title: List<Base> contains different Derived types. How to convert safely with LINQ?
body: <p>I recently ran into a situation where I received a <code>List&lt;Base&gt;</code> when I was expecting a <code>List&lt;Derived&gt;</code>, which is really what I needed.  It turns out that the Derived is a subclass of Base and <code>List&lt;Base&gt;</code> actually contained the Derived objects I needed.</p>
  
  <p>However, the List I'm getting is returned from a third party API and I'm concerned now that it may eventually come back with more than one type that derives from Base.  I need to convert <code>List&lt;Base&gt;</code> to <code>List&lt;Derived&gt;</code> and I want to make sure that I'm only converting the type that I need while safely skipping any other subtypes that aren't related to the one I need.</p>
  
  <p>For instance, if I have the following class hierarchy:</p>
  
  <pre><code>public class Derived : Base {}
  public class DerivedOne : Base {}
  public class Base {public int i;}
  </code></pre>
  
  <p>Then I have the following results from the below code:</p>
  
  <pre><code>static void Main(string[] args)
  {
      List&lt;Base&gt; bList = new List&lt;Base&gt;() {new Derived(), new DerivedOne()};
      List&lt;Derived&gt; dList = new List&lt;Derived&gt;();
      /*InvalidCastException*/
      // dList = bList.ConvertAll(x =&gt; (Derived)x);
  
      /*InvalidCastException*/
      // dList = new List&lt;Derived&gt;(bList.Cast&lt;Derived&gt;());
  
      /*Works, but essentially 'converts' DerivedOne object
       to Derived object, which would be unwanted.*/
      dList = bList.ConvertAll(x =&gt; new Derived{i = x.i});
      // or
      dList = bList.Select(x =&gt; new Derived{i = x.i}).ToList();
  
      /* Works, but is there a cleaner way using LINQ? */
      dList = new List&lt;Derived&gt;();
      foreach(Base b in bList) {
          Derived d = b as Derived;
          if (d != null)
              dList.Add(d);
      }
  }
  </code></pre>
  
  <p>So, my question is this: How can I create a <code>List&lt;Derived&gt;</code> from the <code>List&lt;Base&gt;</code> using LINQ without throwing an InvalidCastException or creating Derived objects from the unrelated DerivedOne class?</p>