Question

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 ?

Was it helpful?

Solution

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

OTHER TIPS

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

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.

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!?

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

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");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top