Arraylist of structure problem

Modifying arraylist

I have an arraylist of a certain class
Private Structure DataStruct
 Dim name
 Dim val
End Structure

Dim list As New ArrayList

And as my program go along I add items to my arraylist(list)
of DataStruct type..]
My problem when i want to search for a certain data(for example
a name) in the list and after that i want to change the val member,
how can I do this without having to use index method

Pls help!
Thanks guys.
 

 



Answer this question

Arraylist of structure problem

  • Kaos

    Consider using a class instead of a structure. Structures copy when boxed, and non-generics collections (System.Collections) uses object[] for internal storage (thus, boxing occurs).. consider the following:

    DataStruct d = new DataStruct(); // superfluous
    d.val = 1;
    myArrayList.Add(d);
    Console.WriteLine(Convert.ToString(((DataStruct)myArrayList[0]).val);
    ((DataStruct)myArrayList[0]).val = 2;
    Console.WriteLine(Convert.ToString(((DataStruct)myArrayList[0]).val);

    Output:
    1
    1

    Using a class will prevent the copying (structs are valuetype subclasses fwiw).

    Also, to avoid having to loop through a list to locate the entry you need to modify you can use a Hashtable instead:

    Hashtable h = new Hashtable();
    DataClass d = new DataClass();
    d.name = "foo";
    d.val = 1;
    h[d.name] = d;
    Console.WriteLine(Convert.ToString(((DataClass)h[0]).val);
    ((DataClass)h["foo"]).val = 2
    Console.WriteLine(Convert.ToString(((DataClass)h[0]).val);

    Output:
    1
    2

    If you're using .net 2.0 you should use a Dictionary<> (generics) instead of a Hashtable and a List<> instead of an ArrayList.

    Hope that helps, sorry for the C# it's what I'm used to.





  • Deepak Rangarajan

    Thanks for your reply.
    I have a question though.
    In line:
    Console.WriteLine(Convert.ToString(((DataStruct)myArrayList[0]).val);
    Is 0 ihe arraylist index I can't really use it since I really don't know
    what index of the array to look for....

    An off topic question though, you said that I'd better use a class Right
    now I'm declaring the structure inside a class.Is it ok for me to declare a class
    inside another class

    Thanks for your time.


  • Yeghia Dolbakyan

    Yes in my example [0] is just an index, i only used '0' for the example.

    Like i said, though, using a Dictionary/Hashtable would allow you to say ["Name"] instead of having to find the correct index at all.

    I'm a C# programmer and in C# there's no problems clearing classes within classes (inner types). I don't see why it wouldn't work in VB.NET, but seeing as I've never seen or tried it myself, I can't say for sure (wouldn't hurt to try it out though).



  • Arraylist of structure problem