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?

3

1 Answer 1

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#.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
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 :)
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<T> or a regular array of the class objects.
@Tim oops.. You are right, ArrayList will have performance issues of boxing/unboxing :|. Now, I guess OP has to go with List<T>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.