title: What is the best way to sort xml elements by attribute values in c#/.net 3.5
body: <p>I have a XML file with data like:</p>
  
  <pre><code>&lt;Details&gt;
    &lt;TableDef&gt;
      &lt;Column Name="Calldate" HeaderName="Calldate" SourceColumnName="Calldate" IsHidden = "false" Position="4" /&gt;
      &lt;Column Name="Issue" HeaderName="Issues" SourceColumnName="Issues" IsHidden = "false" Position="3" /&gt;
      &lt;Column Name="ParamortizedValue" HeaderName="paramortizedvalue" SourceColumnName="Value" IsHidden = "false" Position="1" /&gt;
      &lt;Column Name="PercentBondTotal" HeaderName="percentbondtotal" SourceColumnName="Percentage" IsHidden = "false" Position="2" /&gt;
    &lt;/TableDef&gt;
  &lt;/Details&gt;
  </code></pre>
  
  <p>I was wondering what would be the best and efficient way to filter and sort the elements by an attribute so that I can use that sorted elements further in my code?</p>
  
  <p>In above example, I want to filter by "IsHidden = false" and then sort the elements by "Position" attribute.</p>
  
  <p>I have the following code that will read all the elements without any sort:</p>
  
  <pre><code>var doc = XDocument.Load("data.xml");
  var nodeTableDefInfo = doc.XPathSelectElements("/Details");
  var elements = nodeTableDefInfo.Elements("TableDef").Elements();
  foreach (var e in elements)
  {
    //want to work on the sorted elements
  }
  </code></pre>
  
  <p>Guys, Thanks for all the solutions. before I could read your solution I came up with this:</p>
  
  <pre><code>var elements = nodeTableDefInfo.Elements("TableDef").Elements();
  var sortedElements = (from element in elements 
                  where element.Attribute("IsHidden").Value == "false" 
                  orderby element.Attribute("Position").Value ascending 
                  select element);
  foreach (var e in sortedElements)
  {
  //work on the sorted elements
  }
  </code></pre>
  
  <p>Now, after going through the solutions, I really liked the solution and explanation provided by <code>GFK</code>. I guess I need some handling for nulls. Thanks all.</p>