views:

223

answers:

3

Was looking at some code earlier, and am thinking that there has to be a more elegant way of writing this....

(returnVar.Warnings is a string array, it could be returned as any size depending on the number of warnings that are logged)

For Each item In items
  If o.ImageContent.ImageId = 0 Then
    ReDim Preserve returnVar.Warnings(returnVar.Warnings.GetUpperBound(0) + 1)
    returnVar.Warnings(returnVar.Warnings.GetUpperBound(0)) = "Section: " & section.<header>.<title>.ToString & " , Item: " & item.<title>.ToString
  End If
Next
+5  A: 

use the generic List(of string) then get an array containing the list data if you need it

dim list = new List(of string)
list.Add("foo")
list.Add("bar")
list.ToArray()
Jason
Note: The ToArray method doesn't return the underlying array, it creates a new array and copies the values to it.
Guffa
good point, post updated
Jason
A: 

Can't you use ArrayList which does this for you?

http://msdn.microsoft.com/en-us/library/system.collections.arraylist.aspx

Martin Peck
arraylist is something that should go away, it's not typesafe, use List(of T)
Fredou
A: 

Start by moving the If statement out of the loop.

If you are using framework 3.5, you can use LINQ to loop the items.

If o.ImageContent.ImageId = 0 Then
 returnVar.Warnings = items.Select(Function(item) "Section: " & section.<header>.<title>.ToString & " , Item: " & item.<title>.ToString).ToArray()
Else
 returnVar.Warnings = New String() {}
End If
Guffa