0

I'm unsure how to change List<int> to a specified array and return each element. I'm trying to create the method for returning the array.

    using System;
    using System.Collections.Generic;

    namespace RandomArray
    {
        public class RandomArrayNoDuplicates
        {
            static Random rng = new Random();
            static int size = 45;
            static int[] ResultArray;
            static void Main()
            {
                int[] ResultArray = InitializeArrayWithNoDuplicates(size);
                Console.ReadLine();
            }


            /// <summary>
            /// Creates an array with each element a unique integer
            /// between 1 and 45 inclusively.
            /// </summary>
            /// <param name="size"> length of the returned array < 45
            /// </param>
            /// <returns>an array of length "size" and each element is
            /// a unique integer between 1 and 45 inclusive </returns>
            public static int[] InitializeArrayWithNoDuplicates(int size)
            {
                List<int> input = new List<int>();
                List<int> output;

                //Initialise Input
                for (int i = 0; i < size; i++)
                {
                    input[i] = i;
                }
                //Shuffle the array into output
                Random rng = new Random();
                output = new List<int>(input.Capacity);
                for (; input.Capacity > 0;)
                {
                    int index = rng.Next(input.Capacity);
                    int value = input[index];
                    input.Remove(index);
                    output.Add(value);
                }
                return; // Returning the final array here with each element
            }
        }
    }  

Is there an equivalent method for the List<int> type to work with just arrays as opposed to using a list then converting back to arrays? And should I use a different system library reference?

Marvin
  • 229
  • 1
  • 3
  • 11
  • 1
    Not sure what you are trying to do... Not very clear. But from list to array and back then you have `.ToList( )` and `ToArray()` – Gilad Green Aug 27 '17 at 09:45
  • 1
    You are mistaking `input.Length` with `input.Capacity`. `Capacity` does not, in general, change when an item is removed from the list. `Length` does. – Ondrej Tucny Aug 27 '17 at 09:48

2 Answers2

1

using .ToArray for the list like so:

list.ToArray();

For the vice versa you can use .ToList also,

OmG
  • 18,337
  • 10
  • 57
  • 90
1

There is, you can always swap two array elements by hand without using any list:

public static void Swap<T>(T[] array, int i, int j)
{
    T temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}
AgentFire
  • 8,944
  • 8
  • 43
  • 90