RingDotNetfor Ring

Collections and LINQ

Lists, dictionaries, sets, queues and stacks, how to sort them, and how to ask questions about them with LINQ.

What you will learn#

Which collection?#

CollectionUse it when...Ring class
Listyou need items in order, and to find them by positionStringList, NumberList, ObjectList
Dictionaryyou look items up by a key (a name, an id)StringDictionary, NumberDictionary, ObjectDictionary
Seteach value may appear only onceStringSet
Queuefirst in, first out (a line of customers)StringQueue
Stacklast in, first out (undo)StringStack

Ring lists are flexible and fine for most programs. Use .NET collections when you need their special behavior (a set, a queue), speed with big data, or when a .NET method asks for one.

The program#

samples/UsingDotNet/tutorials/ch01_collections.ring
# collections and LINQ - lists, dictionaries, sets, queues, sorting and querying
load "dotnet.ring"

using {
	"System.Collections.Generic"
	"System.Linq"
}

func main

	# A list keeps items in order
	oFruit = new StringList()
	oFruit.Add("banana")
	oFruit.Add("apple")
	oFruit.Add("cherry")
	? "Count             : " + oFruit.Count
	? "Second item       : " + oFruit.Item(1)
	oFruit.Sort(NULL)
	? "After Sort        : " + list2str(oFruit.toList())
	? "Contains apple    : " + oFruit.Contains("apple")
	? "Index of cherry   : " + oFruit.IndexOf("cherry")

	# A dictionary maps keys to values
	oAges = new NumberDictionary()
	oAges.SetItem("Ann",31)
	oAges.SetItem("Bob",17)
	? "Ann is            : " + oAges.Item("Ann")
	aFound = oAges.TryGetValue("Cy")
	? "Is Cy known?      : " + aFound[1]
	? "Keys              : " + oAges.Count + " keys"

	# A set holds each value once
	oSet = new StringSet()
	oSet.Add("red") oSet.Add("green") oSet.Add("red")
	? "Set size          : " + oSet.Count + " (red was added twice)"

	# A queue is first-in first-out, a stack is last-in first-out
	oQueue = new StringQueue()
	oQueue.Enqueue("first") oQueue.Enqueue("second")
	? "Queue gives       : " + oQueue.Dequeue()
	oStack = new StringStack()
	oStack.Push("first") oStack.Push("second")
	? "Stack gives       : " + oStack.Pop()

	# LINQ asks questions about a collection: the code of each question is Ring code
	aSales = [120, 45, 300, 15, 210, 99, 81]
	aBig = dnQuery(aSales).Where("xDotNetResult = aDotNetArgs[1] >= 100").OrderByDescending("xDotNetResult = aDotNetArgs[1]").ToList()
	? "Sales >= 100      : " + joinList(aBig)
	? "Count, sum, max   : " + dnQuery(aSales).Count() + ", " + dnQuery(aSales).Sum("") + ", " + dnQuery(aSales).Max("")
	? "Any over 250?     : " + dnQuery(aSales).Any("xDotNetResult = aDotNetArgs[1] > 250")
	? "Average           : " + dnQuery(aSales).Average("")

# the items of a Ring list on one line
func joinList aList

	cText = ""
	for xItem in aList
		if cText != ""
			cText += ", "
		ok
		cText += xItem
	next
	return cText
Output
Count             : 3
Second item       : apple
After Sort        : apple
banana
cherry
Contains apple    : 1
Index of cherry   : 2
Ann is            : 31
Is Cy known?      : 0
Keys              : 2 keys
Set size          : 2 (red was added twice)
Queue gives       : first
Stack gives       : second
Sales >= 100      : 300, 210, 120
Count, sum, max   : 7, 870, 300
Any over 250?     : 1
Average           : 124.29

How it works#

A list#

Add adds, Count counts, Item(1) reads by position (the first item is position 0), Sort(NULL) sorts in place, Contains and IndexOf search. toList() copies the items into a Ring list, so you can use for ... in.

Note

Sort(NULL): Sort has several versions (with a comparer, with a range...). NULL means "the version without parameters".

A dictionary#

SetItem("Ann",31) stores a value under a key; Item("Ann") reads it. TryGetValue("Cy") asks without failing when the key is missing, and returns the list [found, value].

A set#

Adding "red" twice leaves one "red". Sets also have Union, Intersect and Except for combining.

Queue and stack#

A queue gives back the first item added (Enqueue, Dequeue); a stack gives back the last (Push, Pop).

LINQ#

LINQ means language integrated query: ask a collection a question. In RingDotNet, dnQuery(aList) wraps any Ring list or .NET collection. Each step is a call; the code of a question is Ring code in a text: it reads the item as aDotNetArgs[1] and writes its answer into xDotNetResult.

Ring
aBig = dnQuery(aSales).Where("xDotNetResult = aDotNetArgs[1] >= 100").OrderByDescending("xDotNetResult = aDotNetArgs[1]").ToList()

Read it as: from aSales, where the item is at least 100, order by the item, descending, then give a Ring list. Other questions: Count(), Sum(""), Max(""), Average(""), Any(code), Select(code), Take(n), Skip(n), Distinct(). An empty "" means "the item itself". The complete list is in Collections & LINQ.

What you learned#

Exercises#

  1. Put the numbers 5, 3, 8, 3, 1 into a NumberList, sort it, and print it.
  2. Count how many times each word appears in a sentence with a NumberDictionary.
  3. Use a StringStack to reverse the letters of a word.
  4. With LINQ: from [3,8,12,5,20] get the numbers above 4, doubled (Select), and their sum.

Next#

Files and folders

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