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#
- the five common collections and when to use each,
- how to get a collection's items back into a Ring list,
- LINQ: filter, sort and summarize with a few calls.
Which collection?#
| Collection | Use it when... | Ring class |
|---|---|---|
| List | you need items in order, and to find them by position | StringList, NumberList, ObjectList |
| Dictionary | you look items up by a key (a name, an id) | StringDictionary, NumberDictionary, ObjectDictionary |
| Set | each value may appear only once | StringSet |
| Queue | first in, first out (a line of customers) | StringQueue |
| Stack | last 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#
# 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 cTextCount : 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.29How 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.
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.
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#
- choose the collection by the question you ask of it,
toList()brings a .NET collection to Ring,TryGetValueandNULLfor methods with several versions,- LINQ answers questions in one chain.
Exercises#
- Put the numbers
5, 3, 8, 3, 1into aNumberList, sort it, and print it. - Count how many times each word appears in a sentence with a
NumberDictionary. - Use a
StringStackto reverse the letters of a word. - With LINQ: from
[3,8,12,5,20]get the numbers above 4, doubled (Select), and their sum.