Collections & LINQ
Typed .NET collections with Ring syntax, indexers, copying to Ring lists, and LINQ queries over Ring lists or any .NET collection.
Typed collections#
The common closed generic collections have ready-made classes (using { "System.Collections.Generic" }):
| Class | .NET type |
|---|---|
StringList, NumberList, ObjectList | List<string>, List<double>, List<object> |
StringDictionary, NumberDictionary, ObjectDictionary | Dictionary<string, T> |
StringSet | HashSet<string> |
StringQueue, StringStack | Queue<string>, Stack<string> |
using { "System.Collections.Generic" }
oList = new StringList()
oList.Add("banana") oList.Add("apple") oList.Add("cherry")
oList.Sort(NULL)
? oList.Count
aItems = oList.toList() # toList() copies the collection to a Ring list
for cItem in aItems
? cItem
next
oDict = new StringDictionary()
oDict.SetItem("two","2") # indexers: Item(index) and SetItem(index, value)
? oDict.Item("two")
aResult = oDict.TryGetValue("three") # out parameters come back as a list
? aResult[1] # 0samples/UsingDotNet/introduction/test03_collections.ring
# Collections: the generated closed generic classes (StringList, StringDictionary ...)
load "dotnet.ring"
using { "System.Collections.Generic" }
# List<string>
oList = new StringList() {
Add("banana")
Add("apple")
Add("cherry")
}
oList.Sort(NULL)
? "Count = " + oList.getCount()
? "First = " + oList.Item(0)
oList.SetItem(0,"avocado")
? "Contains(apple) = " + oList.Contains("apple")
aItems = oList.toList()
for cItem in aItems
? " " + cItem
next
# List<double>
oNums = new NumberList()
for nLoop = 1 to 5
oNums.Add(nLoop * nLoop)
next
? "Numbers : " + list2str(oNums.toList())
# Dictionary<string,string>
oDict = new StringDictionary()
oDict.Add("one","1")
oDict.SetItem("two","2")
? "Dict count = " + oDict.getCount()
? "two = " + oDict.Item("two")
? "has one = " + oDict.ContainsKey("one")
? "keys = " + list2str(oDict.getKeys().toList())
# Dictionary<string,object> (numbers and strings)
oObj = new ObjectDictionary()
oObj.SetItem("pi",3.14159)
oObj.SetItem("name","Ring")
? string(oObj.Item("pi")) + " " + oObj.Item("name")
# Set, Queue, Stack
oSet = new StringSet()
oSet.Add("a") oSet.Add("b") oSet.Add("a")
? "Set count = " + oSet.getCount()
oQ = new StringQueue()
oQ.Enqueue("first") oQ.Enqueue("second")
? "Dequeue = " + oQ.Dequeue()
oS = new StringStack()
oS.Push("bottom") oS.Push("top")
? "Pop = " + oS.Pop()Count = 3
First = apple
Contains(apple) = 0
avocado
banana
cherry
Numbers : 1
4
9
16
25
Dict count = 2
two = 2
has one = 1
keys = one
two
3.14 Ring
Set count = 2
Dequeue = first
Pop = topTo add your own closed generic type, add a line to the :types list of its namespace in tools/dotnettools/dotnetmanifest.ring and run the generator (Class generator shows the line). Without a class, dnNewGeneric(...) gives you the object and callMethod works on it.
Other collection classes#
System.Collections, System.Collections.Specialized, System.Collections.Concurrent and System.Collections.ObjectModel are wrapped completely: ArrayList, Hashtable, SortedList, Stack, Queue, BitArray, NameValueCollection, ObservableCollection and so on.
samples/UsingDotNet/introduction/test10_collections.ring
# Collections of the .NET class library: dictionaries and the specialized and generic collections
load "dotnet.ring"
using {
"System.Collections"
"System.Collections.Specialized"
"System.Collections.Generic"
}
# Word frequency with Dictionary<string,double> (entries are wrapped KeyValuePair objects)
oCount = new NumberDictionary()
aWords = split("the quick brown fox jumps over the lazy dog the end"," ")
for cWord in aWords
aGot = oCount.TryGetValue(cWord)
nOld = 0
if aGot[1] nOld = aGot[2] ok
oCount.SetItem(cWord,nOld + 1)
next
? "Distinct words : " + oCount.Count
? "'the' appears : " + oCount.Item("the") + " times"
aPairs = oCount.toList()
for oPair in aPairs
if oPair.Value > 1 ? " " + oPair.Key + " = " + oPair.Value ok
next
# Sorted collections and a priority queue
oSet = new SortedStringSet()
for cName in ["pear","apple","fig","apple","banana"] oSet.Add(cName) next
? "Sorted set : " + list2str(oSet.toList())
oTasks = new StringPriorityQueue()
oTasks.Enqueue("write docs",3) oTasks.Enqueue("fix bug",1) oTasks.Enqueue("release",2)
? "Next task : " + oTasks.Dequeue()
? "Then : " + oTasks.Dequeue()
# Non-generic and specialized collections
oList = new ArrayList()
oList.Add(3) oList.Add(1) oList.Add(2)
oList.Sort(NULL)
? "ArrayList : " + oList.Item(0) + oList.Item(1) + oList.Item(2)
oQuery = new NameValueCollection()
oQuery.Add([ :name = "tag", :value = "ring" ]) oQuery.Add([ :name = "tag", :value = "dotnet" ]) oQuery.Add([ :name = "page", :value = "2" ])
? "Query values : " + oQuery.Item("tag") + " | " + oQuery.Item("page")
func split cText, cSep
return str2list(substr(cText,cSep,nl))Distinct words : 9
'the' appears : 3 times
the = 3
Sorted set : apple
banana
fig
pear
Next task : fix bug
Then : release
ArrayList : 123
Query values : ring,dotnet | 2Sorting and searching with Ring code#
Methods that take a delegate (Predicate, Comparison, Action) accept dnCallback(...). The Ring code reads aDotNetArgs and sets xDotNetResult:
oList.FindAll(dnCallback("xDotNetResult = left(aDotNetArgs[1],1) = 'a'"))
oList.Sort([ :comparison = dnCallback("xDotNetResult = len(aDotNetArgs[1]) - len(aDotNetArgs[2])") ])
oList.@ForEach(dnCallback("? aDotNetArgs[1]"))See Callbacks & events.
LINQ#
using { "System.Linq" } loads Enumerable and a fluent wrapper, dnQuery(...), that works on a Ring list or any .NET collection. The lambda is Ring code: it reads aDotNetArgs[1] and writes xDotNetResult.
using { "System.Linq" }
aSales = [120, 45, 300, 15, 210, 99, 81]
aTop = dnQuery(aSales).Where("xDotNetResult = aDotNetArgs[1] >= 100").OrderByDescending("xDotNetResult = aDotNetArgs[1]").Take(3).ToList()
? dnQuery(aSales).Count()
? dnQuery(aSales).Sum("")
? dnQuery(aSales).Average("")
? dnQuery(aSales).Max("")samples/UsingDotNet/introduction/test11_linq.ring
# LINQ over Ring lists and strings: the conditions are Ring code
load "dotnet.ring"
using { "System.Linq" }
# Where, OrderBy, Count, Sum, Any ... take a condition written as Ring code (aDotNetArgs[1] is the item)
aSales = [120, 45.5, 300, 80, 15, 210, 99.9]
aBig = dnQuery(aSales).Where("xDotNetResult = aDotNetArgs[1] >= 100").OrderByDescending("xDotNetResult = aDotNetArgs[1]").ToList()
? "Sales >= 100 (high to low) : " + list2str(aBig)
oAll = dnQuery(aSales)
? "Count / Sum / Average : " + oAll.Count() + " / " + oAll.Sum("") + " / " + oAll.Average("")
? "Min / Max : " + oAll.Min("") + " / " + oAll.Max("")
? "Any over 250 ? : " + oAll.Any("xDotNetResult = aDotNetArgs[1] > 250")
? "All positive ? : " + oAll.All("xDotNetResult = aDotNetArgs[1] > 0")
# Strings: select, distinct, order, skip/take
aNames = ["Ring","dotnet","Ring","linq","Lua","dotnet","Python"]
? "Distinct upper-cased : " + list2str(dnQuery(aNames).Distinct().Select("xDotNetResult = upper(aDotNetArgs[1])").ToList())
? "Second to fourth by length: " + list2str(dnQuery(aNames).Distinct().OrderBy("xDotNetResult = len(aDotNetArgs[1])").Skip(1).Take(3).ToList())
# The raw Enumerable class: type arguments are inferred
oLinq = new Enumerable()
? "Enumerable.Last : " + oLinq.Last(aNames)Sales >= 100 (high to low) : 300
210
120
Count / Sum / Average : 7 / 870.40 / 124.34
Min / Max : 15 / 300
Any over 250 ? : 1
All positive ? : 1
Distinct upper-cased : RING
DOTNET
LINQ
LUA
PYTHON
Second to fourth by length: Ring
linq
dotnet
Enumerable.Last : PythonThe dnQuery methods#
| Group | Methods |
|---|---|
| Filtering and projection | Where(code), Select(code), SelectMany(code), TakeWhile(code), SkipWhile(code) |
| Ordering | OrderBy(code), OrderByDescending(code), ThenBy(code), ThenByDescending(code), Reverse() |
| Paging | Take(n), Skip(n), Distinct() |
| Sets | Concat(other), Union(other), Intersect(other), Except(other) |
| Results | ToList(), Count(), CountWhere(code), First(), FirstWhere(code), Last(), ElementAt(n) |
| Tests | Any(code), All(code), Contains(value) |
| Aggregates | Sum(code), Average(code), Min(code), Max(code) — an empty "" means the value itself |
The generic LINQ methods of Enumerable also work directly: the bridge infers the type arguments from the values you pass, and callbacks become Func<object, ...> delegates.
Where to go next#
- Callbacks & events: the code you pass to
Where,Selectand the other LINQ methods is a callback. - The tutorial chapter Collections and algorithms.