简体   繁体   中英

C# assigning array element to another array

I am making a program which browses files, puts them into an array, and then the user puts those files in a random order into a new array called playlist.

To be clear I do not want to assign one array to the other array. I only want to assign one of the many elements of one array to another existing array.

How is this done?

Here is all I can think of:

playlist[1] = files[5];

You can utilize the System and System.IO namespace for all that fairly easily.

var files = Directory.GetFiles("directory path");
var playlist = new string[files.Length];

At that point, you'll have two arrays. The files array will contain the full path for every file in the directory you specified, and playlist will be a string array with the same size as the files array.

To get a random file and assign it to the playlist array, you can use the Random class in the System namespace to get a random number between a range.

var random = new Random();
int index = random.Next(0, playlist.Length);

You can use a bunch of logical statements to make sure that you don't copy over one file more than once, and that the space you're copying it to isn't already taken up by a file. But you had the idea idea. Transferring all the paths would look something like this

playlist[RandomPlaylistIndex] = files[RandomFileIndex];

with the lefthand side being the receiving end. That's pretty much the gist of it, anyhow. I can post more code if you're still stuck.

Use Array.Copy where you can define the Start and End of the source Array.

For instance, to copy the 15th element of Files to PLaylist:

  Array.Copy(Files, 15, 1, Playlist, Playlist.Length,1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM