Welcome to AspAdvice Sign in | Join | Help

Limit Rows In DataTable or DataSet

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();
    }
}

Published Tuesday, October 30, 2007 3:30 PM by ssmith
Filed under: , , ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Limit Rows In DataTable or DataSet

Don't forget BeginLoadData,LoadDataRow, EndLoadData in case there are many of those rows :-)

It's been discussed in the past: http://weblogs.asp.net/rosherove/archive/2004/01/22/61541.aspx althought thats for manually converting a datareader to dt/dt as fast as possible.

Tuesday, October 30, 2007 3:39 PM by joteke

# re: Limit Rows In DataTable or DataSet

This is also an interesting read:

DataView vs DataTable.Select

http://blog.hill-it.be/post/2007/10/03/DataView-vs-DataTableSelect

Tuesday, October 30, 2007 4:52 PM by Raj Kaimal

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below