title: How to implement generic method approach using Linq and XML
body: <p>Alright, I think I have some duplicate code that can lend itself to the use of generics.</p>
  
  <p>I have two different Xml files that I open, query, and return as collections that are bound to GridViews.  The collections are Lists of custom classes populated with data from the xml.  Each gridview has its corresponding custom class.  Currently I have two, and say the names of these classes are <strong>XmlDataSource1</strong> and <strong>XmlDataSource2</strong>.</p>
  
  <p>Here's an example of what's working currently using the XmlDataSource1 as the example. Note that the constructor of the XmlDataSource1 object takes the XElements from the query and populates itself. Nothing crazy.</p>
  
  <pre><code>GridView gv = new GridView();
  gv.DataSource = GetXmlDataSource1(pathToXmlFile);
  gv.DataBind();
  
  public List&lt;XmlDataSource1&gt; GetXmlDataSource1(string pathToXmlFile)
  {
     XDocument xml = XDocument.Load(pathToXmlFile);
     IEnumerable&lt;XmlDataSource1&gt; query = from s in xml.Descendants("NodeForXml1")
                                         select new XmlDataSource1(s);
  
     // Where clauses based on user inputs (deferred execution)
     query = query.Where(x =&gt; x.ID = SomeUserInputId);
  
     // More of these where clauses if they have inputs for them...
  
     // Convert to a List and return
     return query.ToList();
  }
  </code></pre>
  
  <p>Now, to implement the GetXmlDataSource2() method, it's like 98% the same.  The major differences are, of course, the select portion of the linq query creating new instances of XmlDataSource2 object, the <em>"NodeForXml2"</em> descendants target node, and some where clauses that apply/do not apply. </p>
  
  <p>How can I make these GetXmlDataSource# methods generic?  Ideally I'd like to call it as stated below and here's what I've tried but I can't get the select portion of the linq query to call the constructor of the correct data object.</p>
  
  <pre><code>GridView gv1 = new GridView();
  GridView gv2 = new GridView();
  
  gv1.DataSource = GetXmlDataSource&lt;XmlDataSource1&gt;(pathToXmlFile);
  gv2.DataSource = GetXmlDataSource&lt;XmlDataSource2&gt;(pathToXmlFile);
  
  gv1.DataBind();
  gv2.DataBind();
  
  public List&lt;T&gt; GetXmlDataSource&lt;T&gt;(string pathToXmlFile)
  {
     // The type of T in case I need it
     Type typeOfT = typeof(T);
  
     XDocument xml = XDocument.Load(pathToXmlFile);
  
     // How to make new XmlDataSource1 and 2 objects?? This statement doesn't work.
     IEnumerable&lt;T&gt; query = from s in xml.Descendants("NodeForXml1")
                            select new T(s);
  
  
  
     // How to return the IEnumerable query to a List of the T's?
     return query.ToList();
  }
  </code></pre>
  
  <p>How far away am I?  Am I close?</p>