Will Collection.ToArray() function keep the order of its items?

A

Andrew

Hello, friends,

We have a .net 2005 app. I need to pass 2 arrays to a method:
UserInfoUpdate(dataType1[] array1, dataTyep2[] array2).

The items in these 2 arrays have 1-1 relations, i.e., the first item in
array1 must be updated together with the first item in array 2, vice versa,
and the same for the rest of items.

Since I don't know how many items I can find, I use collection1 and
collection2 instead so that I can use its Add() function to add as many
(little) item as needed.

Then I use

array1 = collection1.ToArray();
array2 = collection2.ToArray();

and then pass array1 and array2 into UserInfoUpdate().

However, one thing I am not sure is: Will collection.ToArray() function keep
the order of items in the collection or not? In another word, items in the
returned array will have EXACTLY the same order in its original collection?

(As you know, if ToArray() cannot keep the same order, we may update user
info wrongly by relying on index value)

Thanks a lot for your help.
 
M

Marc Gravell

Yes, the standard implementations of both ToArray() and CopyTo() will
preserve order - however, personally I'd go for an implementation that
passed an array of the composite object - i.e. a SomeType[] where
SomeType has a DataType1 "Foo" and a DataType2 "Bar" - heck,
KeyValuePair<DataType1,DataType2> would do (although I'd probably create
something more meaningful).

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top