views:

456

answers:

6

Hi,

I have a news portal.

For this portal I have a database with a "News" table and with the following columns (NewsID, CategoryID, NewsTitle, NewsText, DateAdded, ImagePath, TotalRead, NewsType, isActive)

I use dataset files (.xsd) and for this one, I have a query that returns the last 3 days' news into a custom class that I coded, named HHNews.

HHNews Class has a function that returns a strongly-typed datatable that includes the results of the query I mention above.

The home page has different sections for news.. these are; - Headlines (5 items) - Sub-headings (4 items) - Last 5 news items for each of the news categories...( categories are like; sports, local news, economics,

For the home page, I retrieve the datatable returned from the class. Now I want to query this datatable and build the sections I mention above.. e.g.

if my datatable is called "dt", then is there a way to sql-like query this dt such as "select TOP(5) NewsID, NewsTitle, NewsText from dt where NewsType = 0" -- 0 representing the headline ?

+1  A: 

You can use LINQ to DataSet if you're in .NET 3.5.

Dave Cluderay
A: 

You can use the default view to filter the datatable like so:

dt.DefaultView.RowFilter = "NewsType = 0";

Not sure how you would get the top 5!?

Rigobert Song
A: 

If you aren't in .NET 3.5, you can create a DataView based on the DataTable object and then set the RowFilter property on the DataView. For example:

DataView myDV = new DataView(dt);
myDV.RowFilter = "NewsType = 0";

You can then catch only the first 5 rows in your DataView.

Scott Anderson
A: 

Absolutely. You can use LINQ as Dave Cluderay mentioned. To retrieve your headlines, for example, you could run:

var myDataTable = dt.AsEnumerable();
var headlines = myDataTable.Where(t => t.NewsID == 0).Take(5);
Chris Pebble
thanks for the answer chris.. Is this solution fast?
Emin
Yes, I've never found my bottleneck to be LINQ. Of course it does depend on how many news stories you are pulling back. If it's more then a hundred or two you may want to consider running this logic inside your database and returning just the records you need.
Chris Pebble
A: 

If you're not in 3.5 you could use a simple for loop to get the top 5 rows after sorting the table.

Fermin
A: 

There is a Select method on the Datatable, dont think there is a way to limit the amount returned. I like the LINQ way, but just an alternative....but the limit might count this out.

dt.Select("NewsType = 0");
CSharpAtl