Question

In my VB code I am reading all the news from database, there are hundreds of them:

For Each lnews In ltable.Rows
    Dim litem = lcontent
    litem = litem.Replace("%Headline%", _
                Web.HttpUtility.HtmlEncode(lnews("Headline")))
Next

I need to get just 3 latest ones. What is the best way to do it?

For i As Integer = 0 To 2
     Dim s = ltable.Rows(i)
Next i
Was it helpful?

Solution

I'm not sure about definition of "the best way" here, but you can get last 3 rows from DataTable using LINQ like this :

For Each s In ltable.AsEnumerable().Skip(ltable.Rows.Count() - 3)
    's is a DataRow here
Next

or without LINQ :

Dim count = ltable.Rows.Count()
For i As Integer = count - 4 To count - 1
    Dim s = ltable.Rows(i)
Next i

OTHER TIPS

You should probably avoid returning more rows than necessary from your database wherever possible, there is no point in returning 100+ rows of data if you only require the use of the top 3 as it will just increase the query time as you get more and more headlines in your database.

If you do need them all to be returned but just require the first three (or last three) then you can use LINQ as already posted by har07.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top