RingDotNetfor Ring

Tabular data

Rows and columns are everywhere — spreadsheets, CSV files, database results. This lesson reads a CSV text into a DataTable, then filters, sorts, summarises and writes it back.

What you will learn#

CSV#

CSV (comma separated values) is the simplest table format: a header line with the column names, then one line per row with the values separated by commas.

Region,Seller,Amount
North,Ann,1200
South,Bob,800

Spreadsheets, databases and many programs read and write it.

Note

Real CSV files can contain commas inside quoted values ("Smith, John"). This tutorial's data has none, so splitting on commas is enough. For messy files use a CSV library (a NuGet package, the tutorial A library written in C#) or a regular expression.

The program#

samples/UsingDotNet/tutorials/ch09_tables.ring
# tabular data - read a CSV text, use a DataTable, filter, sort, summarise, write a CSV
load "dotnet.ring"

using {
	"System"
	"System.Data"
	"System.IO"
}

func main

	# STEP 1. The data: a CSV text (comma separated values): a header line and one line per row
	cCsv = "Region,Seller,Amount" + nl +
		"North,Ann,1200" + nl +
		"South,Bob,800" + nl +
		"North,Cy,450" + nl +
		"East,Dee,2000" + nl +
		"South,Eve,300" + nl +
		"North,Ann,700"

	# STEP 2. A DataTable has typed columns and rows
	oTable = new DataTable()
	oTable.Columns.Add([ :columnName = "Region", :type = "System.String" ])
	oTable.Columns.Add([ :columnName = "Seller", :type = "System.String" ])
	oTable.Columns.Add([ :columnName = "Amount", :type = "System.Int32" ])
	aLines = str2list(cCsv)
	for nLine = 2 to len(aLines)                         # line 1 is the header
		aFields = str2list(substr(aLines[nLine],",",nl))
		oTable.Rows.Add([aFields[1],aFields[2],number(aFields[3])])
	next
	? "STEP 2: " + oTable.Rows.Count + " rows, " + oTable.Columns.Count + " columns"

	# STEP 3. Compute: SUM, AVG, MIN, MAX, COUNT over all rows or those that match a filter
	? nl + "STEP 3: total          : " + oTable.Compute("SUM(Amount)","")
	? "        North total      : " + oTable.Compute("SUM(Amount)","Region = 'North'")
	? "        biggest sale     : " + oTable.Compute("MAX(Amount)","")
	? "        sales over 500   : " + oTable.Compute("COUNT(Amount)","Amount > 500")

	# STEP 4. A DataView sorts and filters without changing the table
	oView = oTable.DefaultView
	oView.Sort = "Amount DESC"
	? nl + "STEP 4: top three sales:"
	for nIndex = 0 to 2
		? "        " + oView.Item(nIndex).Item("Seller") + "  " + oView.Item(nIndex).Item("Amount")
	next
	oView.RowFilter = "Region = 'South'"
	? "        rows in the South: " + oView.Count
	oView.RowFilter = ""

	# STEP 5. Totals per region: collect the regions, then compute for each
	aRegions = []
	for nIndex = 0 to oTable.Rows.Count - 1
		cRegion = oTable.Rows.Item(nIndex).Item("Region")
		if find(aRegions,cRegion) = 0
			aRegions + cRegion
		ok
	next
	aRegions = sort(aRegions)
	? nl + "STEP 5: totals per region:"
	for cRegion in aRegions
		? "        " + cRegion + "  " + oTable.Compute("SUM(Amount)","Region = '" + cRegion + "'")
	next

	# STEP 6. Write the table back as CSV
	cOut = "Region,Seller,Amount" + nl
	for nIndex = 0 to oTable.Rows.Count - 1
		oRow = oTable.Rows.Item(nIndex)
		cOut += oRow.Item("Region") + "," + oRow.Item("Seller") + "," + oRow.Item("Amount") + nl
	next
	cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_tables.csv"])
	new File().WriteAllText([ :path = cFile, :contents = cOut ])
	? nl + "STEP 6: wrote " + len(new File().ReadAllLines(cFile).toList()) + " lines to a CSV file"
	new File().Delete(cFile)
Output
STEP 2: 6 rows, 3 columns

STEP 3: total          : 5450
        North total      : 2350
        biggest sale     : 2000
        sales over 500   : 4

STEP 4: top three sales:
        Dee  2000
        Ann  1200
        Bob  800
        rows in the South: 2

STEP 5: totals per region:
        East  2000
        North  2350
        South  1100

STEP 6: wrote 7 lines to a CSV file

How it works#

Step 2: the table#

A DataTable has typed columns: Region and Seller are texts, Amount is an integer (System.Int32). Types matter: sums and sorting treat numbers as numbers, not as text (as text, 800 would sort after 2000). Rows.Add([...]) adds a row; the values are in column order. The program turns the lines into rows: str2list splits the text into lines, substr(line,",",nl) turns the commas into line breaks, and number() converts the amount.

Step 3: Compute#

Compute(expression, filter) evaluates an aggregate over the rows that pass the filter:

ExpressionMeaning
SUM(Amount)the total
AVG(Amount)the average
MIN(Amount) / MAX(Amount)the smallest / biggest
COUNT(Amount)how many

The filter is a text such as Region = 'North' or Amount > 500: a small SQL-like language. An empty filter means all rows. Text values go in single quotes.

Step 4: a DataView#

A DataView is a window onto the table with its own sort order and filter. oView.Sort = "Amount DESC" sorts, oView.RowFilter = "Region = 'South'" hides other rows, and oView.Count counts what is visible. The table itself is not changed; RowFilter = "" shows everything again. A grid bound to a view (the tutorial Layout and richer controls) updates by itself.

Step 5: groups#

Compute has no "group by". Collect the different regions, then ask for the sum of each: a loop, find to avoid duplicates, sort to order them. (A database does this with GROUP BY; with a SQLite table, groupCount and sqlRows in the tutorial Databases step by step.)

Step 6: writing CSV#

Loop over the rows and build lines. Join the values with commas and the lines with nl. Remember to quote values that contain commas.

What you learned#

Exercises#

  1. Add the average sale per seller.
  2. Sort by region, then by amount descending (oView.Sort = "Region, Amount DESC").
  3. Write only the rows of one region to a new CSV file.
  4. Add a calculated column Commission = Amount * 0.1 (Columns.Add with an Expression).

Next#

Reports with SQL

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.