Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert ArrayList to an array of structure?

Here I have:

Public Structure MyStruct
   Public Name as String
   Public Content as String
End Structure

Dim oStruct as MyStruct = New MyStruct()
oStruct.Name = ...
oStruct.Content = ...

Dim alList as ArrayList = new ArrayList()
alList.Add(oStruct)

I'd like to convert the ArrayList to a static strongly-typed Array of type MyStruct. How can I do that? I had no luck with ToArray.

I am using .NET Framework 2.0.

like image 371
Vincent Avatar asked Oct 09 '08 16:10

Vincent


2 Answers

You have to cast the result of ToArray

MyStruct[] structs = (MyStruct[]) alList.ToArray(typeof(MyStruct));
like image 156
Bill the Lizard Avatar answered Sep 27 '22 16:09

Bill the Lizard


I assume that since you are using ArrayList, you are using 1.1?

In which case, I suspect the following would work:

ArrayList list = new ArrayList();
MyStruct[] array = new MyStruct[list.Count];
list.CopyTo(array); 

(edit - Bill's ToArray usage is more convenient - I didn't know about that one, but then, I very rarely [if ever] use ArrayList)

However, if MyStruct really is a struct, then I cannot say strongly enough that mutable structs are a bad idea - i.e. where you can set .Name and .Content after creation. Structs should almost always be immutable. In reality, your MyStruct looks like it should be a class. Also - I'm not "up" on VB, but are they public fields? Again - not recommended - properties would be preferable. I don't know about VB, but C# 3.0 has some very terse syntax for this:

public class SomeType
{
    public string Name {get;set;}
    public string Content {get;set;}
}

If you are using 2.0 or above, consider List<T> instead of ArrayList.

like image 28
Marc Gravell Avatar answered Sep 27 '22 15:09

Marc Gravell