looping through the values of an ArrayList in C#
Asked Answered
K

5

16

I'm trying to figure out what sort of information these messages contain that are being streamed via OSC. The messages are being stored to an ArrayList. Here is the code:

public void OSCMessageReceived(OSC.NET.OSCMessage message){ 
        string address = message.Address;
        ArrayList args = message.Values;
}

How do I loop through the values of the arrayList args to output its contents?

Karee answered 27/9, 2012 at 16:46 Comment(2)
foreach(Object o in args)Console.WriteLine(o);Jarrell
Note: ArrayList is the old non-generic variant of List<T> and can be used much like List<T>, except that the items are typed as object.Detrude
S
18

you can try with this code

foreach(var item in args )
{
  Console.WriteLine(item);
}
Swisher answered 27/9, 2012 at 16:49 Comment(0)
F
4

You can use a simple for loop:

for (i = 0; i < args.Count; i++)
{
    Console.WriteLine(args[i].ToString());
}

Check out this link here for more info on the C# ArrayList object.

Fick answered 27/9, 2012 at 16:52 Comment(0)
U
3
ArrayList al = new ArrayList(new string[] { "a", "b", "c", "d", "e" });
foreach (var item in al)
{
    Console.WriteLine(item);
}

You can also use a for loop.

for (int i = 0; i < al.Count; ++i)
{
    Console.WriteLine(al[i]);
}
Uniformitarian answered 27/9, 2012 at 16:51 Comment(0)
B
0

Unless you know the type of objects in the ArrayList, your only option is to call the ToString() method on each item.

If you do know the type of objects, you can cast them to the appropriate type and then to print the content in a more intelligent way.

Bara answered 27/9, 2012 at 16:52 Comment(0)
C
-1

Both foreach() and for(int i = 0;...) scroll through all entries of the ArrayList. However it seems that foreach() scrolls through them in the order in which they were added to the ArrayList. With for(int i = 0;...) I observed (Visual Studio 2005) that this is not necessarily true. I experienced in one case that when the objects added to the ArrayList were simple int's it was the case. However when the added objects were of a complex class type the scroll order no longer corresponded to the order in which they had been added to the ArrayList.

Corcovado answered 1/12, 2017 at 9:6 Comment(1)
The two methods are equivalent and should never result in different ordering?Megilp

© 2022 - 2024 — McMap. All rights reserved.