Array to List
Monkey Forums/Monkey Programming/Array to List| 
 | ||
| I was trying not to post something about it and I have it "working" but is there an easier way to turn an array into a list and back. I'm looking to do the stuff below (pseudocode) list:String[] = mystring.Split(",") myList:List = myArray.ToList() Thanks, | 
| 
 | ||
| Also I'm writing a CopyList function but I want it to be generic.  I have a class called Obj for example but I want this to work with all classes. Local tempList:List<Obj> = CopyList(myList) Function CopyList:List<Object>(list:List<Object>) Local temp:List<Object> = New List<Object> For Local o:Object = Eachin list temp.AddLast(o) Next Return temp End function | 
| 
 | ||
| For that second one, you should follow the example of Diddy's 'Arrays' class and bundle it up like this: Class Lists<T> Function Copy:List<T>(list:List<T>) Local temp := New List<T> For Local t := EachIn list temp.AddLast(t) Next Return temp End End Usage: Strict Class Foo Field value:Int Method New(value:Int) Self.value = value End End Class Lists<T> Function Copy:List<T>(list:List<T>) Local temp := New List<T> For Local t := EachIn list temp.AddLast(t) Next Return temp End End Function Main:Int() Local myList := New List<Foo>() myList.AddLast( New Foo(1) ) myList.AddLast( New Foo(2) ) myList.AddLast( New Foo(3) ) Local myCopy := Lists<Foo>.Copy(myList) For Local foo := EachIn myCopy Print foo.value Next Return 0 End | 
| 
 | ||
| Can this also be done with a Stack?  I was using Stack<T> and it didn't work. | 
| 
 | ||
| You don't need all that code: Local arr:String[] = ["a","b","c","d","e"] Local list:List<String> = New List<String>(arr) For Local s:String = Eachin list Print "list item="+s End arr = list.ToArray() For Local i:= 0 Until arr.Length Print "array item "+i+"="+arr[i] End | 
| 
 | ||
| rtfm? :) | 
| 
 | ||
| Oh wow, I never noticed that constructor in the List class before. That means we can cheat for the copying if performance isn't a concern: myCopy = New List( myList.ToArray() ) | 
| 
 | ||
| That would also work for a Stack. | 
| 
 | ||
| Wow thanks...working on this now. | 
| 
 | ||
| Yep works like a charm. The Obj is just a custom class of mine. Local temp_array:Obj[] = Self.obj_stack.ToArray() 'Stack to Array Local temp_stack:Stack<Obj> = New Stack<Obj>(temp_array) 'Array to Stack Local temp_stack:Stack<Obj> = New Stack<Obj>(obj_stack.ToArray()) 'Stack to Stack Local temp_list:List<Obj> = New List<Obj>(obj_stack.ToArray()) 'Stack to List Local temp_stack:Stack<Obj> = New Stack<Obj>(temp_list.ToArray()) 'List to Stack | 
| 
 | ||
| doh I hadn't noticed that either! Wondering now If I have actually needed it in the past.. not sure I have. |