Easiest way to copy values from a collection to an array?

  • Thread starter Thread starter Matthias S.
  • Start date Start date
M

Matthias S.

Hi,

I'm just wondering about the easiest way to copy certain values from a
collection to a simple array.

Say I've got a class (RaceCarDriver) with a DateFirstRace property. Now I'd
like to pass all DateFirstRace-Values in my RaceCarDriverCollection to some
function as a DateTime[].

Any help is greatly appreceated.
 
Matthias,

In this case, you are going to have to create an array yourself, and
populate it. If you wanted to pass the RaceCarDriver array, then you could
just call CopyTo on the collection, and copy to that.

As a matter of fact, if you want, you could take the function that takes
a DateTime array, and have it take an array or collection of RaceCarDriver
instances, and then have the routine get the date time to perform it's
calculations.

I would actually supply both (one that takes DateTime, and another that
takes the collection or array). Factoring out the logic should be easy.

Hope this helps.
 
Hello Matthias,

You have to create a new DataTime array. Since the values are stored in
indivudual instances of the class RaceCarDriver you must enumerate the
entire collection to get the values.

the code would look like this:

// assumes drivers is RaceCarDriverCollection
int id=0;
DateTime[] dates = new DateTime[drives.Count];
foreach (RaceCarDriver driver in drivers) {
dates[id++]=driver.DateFirstRace;
}

Michael
 
Back
Top