1

I need my array to store a bool and string pair.

MyType[,] array1 = { {true, "apple"}, {false, "orange"} };

// Later in my code.
for (i = 0; i < array1.Length; i++)
{
    if(array1[i, 0] == true)
    {
        Console.WriteLine(array1[i, 1]);
    }
}

How do I get the above in C# without using collection? If not possible, which collection should I use?

1 Answers1

3

Arrays can't have different datatypes. It is the design principle of Arrays. Instead, create a class/struct and then create array/list of that class. Something as following,

class MyClass
{
bool flag;
string myStr;
}

List<MyCLass> myList=new List<MyClass>();
ArrayList arrList = new ArrayList(); //or use this option

You should be able to access list using foreach in c#.

Abhishek
  • 6,912
  • 14
  • 59
  • 85
  • yeah i thought of using list but i need to stop looping at the last value of the array or list, as I need to do some string manipulation to the last item. Edit: Reason for using array is it loops faster than list or collection. – Christopher Lim Apr 29 '15 at 05:57
  • You can get the size of list, by using `myList.Count` and then add if clause for the last element while running `foreach`. If you are worried about performance then use ArrayList. Edited answer accordingly :) – Abhishek Apr 29 '15 at 06:00
  • `ArrayList`? Really? I haven't run any benchmarks, but I can almost guarantee that performance with an `ArrayList` will be worse, because of the boxing/unboxing required. Better to use either a `List` or a regular array of the class objects. – Tim Apr 29 '15 at 06:28
  • @Tim oops.. You are right, `ArrayList` will have performance issues of boxing/unboxing :|. Now, I guess OP has to go with `List`. – Abhishek Apr 29 '15 at 06:31