Limit Rows In DataTable or DataSet

Posted by: Steven Smith, on 30 Oct 2007 | View original | Bookmarked: 0 time(s)

I wrote some quick and dirty ADO.NET code to go against an RSS feed instead of a flat XML file today.  In the process I had to figure a way to limit the number of rows returned by the function, which returns a DataTable.  The simplest method I found was this one, which uses the DataTable.Select() method.  Using this technique, you could also pass in a sort parameter (second parameter to Select()) which would let you grab the top N rows from the DataTable after sorting it on whichever column you wished (syntax for sortexpression is "column" which defaults to ascending or "column DESC" for descending).  And of course you can also do a filter, etc., but I didn't need all that.

public DataTable LatestRows(int rowCount)
{
    try
    {

DataSet myDataSet = new DataSet();
using (XmlTextReader myReader = new XmlTextReader("
http://aspalliance.com/crystal.rss"))
{
    myDataSet.ReadXml(myReader);
}

      DataTable myTable = myDataSet.Tables[2].Clone(); // in standard RSS, the feed items are here
      DataRow[] myRows = myDataSet.Tables[2].Select();
      for (int i = 0; i < rowCount; i++)
      {
          if (i < myRows.Length)
          {
              myTable.ImportRow(myRows[i]);
              myTable.AcceptChanges();
          }
      }

      return myTable;
    }
    catch
    {
        return new DataTable();
    }
}
Share this post: email it! | bookmark it! | digg it! | reddit! | kick it! | live it!

Advertisement
Free Agile Project Management Tool from Telerik
TeamPulse Community Edition helps your team effectively capture requirements, manage project plans, assign and track work, and most importantly, be continually connected with each other.
Category: DataSet | Other Posts: View all posts by this blogger | Report as irrelevant | View bloggers stats | Views: 6854 | Hits: 45

News Categories

.NET | Agile | Ajax | Architecture | ASP.NET | BizTalk | C# | Certification | Data | DataGrid | DataSet | Debugger | DotNetNuke | Events | GridView | IIS | Indigo | JavaScript | Mobile | Mono | Patterns and Practices | Performance | Podcast | Refactor | Regex | Security | Sharepoint | Silverlight | Smart Client Applications | Software | SQL | VB.NET | Visual Studio | W3 | WCF | WinFx | WPF | WSE | XAML | XLinq | XML | XSD