7.5. Thoroughly Aggregating Data

LINQ queries help you collect data and report on it from several perspectives, such as how many items, total value, average cost, minimum value, and maximum number. This section shows you how to get results by using aggregation.

7.5.1. Just give me the list and the Count()

You can get the number of rows of data or items in an array by using the extension method Count(). Just tack Count() onto the end of a collection or query result, and you're done! As shown in Figure 7-2, this example gets a list of .aspx files from the Web site's root directory.

Figure 7-2. Counting and displaying ASPX files.

The following code displays the count in a Label control, and the file details (abbreviated in Figure 7-2) in a GridView control:

Try
  Dim q = From f In New System.IO.DirectoryInfo _
         (Server.MapPath("~")).GetFiles() _
         Select f _
         Where f.Extension = ".aspx"
  Label1.Text = "ASPX count: " & q.Count().ToString()
  GridView1.DataSource = q
  GridView1.DataBind()
Catch ex As Exception
  Label1.Text = "Not allowed to do that!"
End Try

In the preceding code, you get the Count() directly from the query result (represented by the variable q) and then convert the number to a string for display.

Notice the use of Try...Catch...End Try in the example. Accessing file information on a Web server might result in permissions errors on the Internet host's system. For more on error ...

Get ASP.NET 3.5 For Dummies® now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.