2017-08-27 68 views
1

我不确定如何将列表更改为指定数组并返回每个元素。我试图创建该方法,所以它必须返回数组。将列表<int>更改为int []

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 
      } 
     } 
    } 

是否有等效的方法为列表类型与数组只是工作,而不是使用一个名单,然后转换回阵列?我应该使用不同的系统库参考吗?

+1

不知道你在做什么......不是很清楚。但从列表到数组,然后你有'.ToList()'和'ToArray()' –

+1

你错误'input.Length'与'input.Capacity'。一般情况下,当物品从列表中删除时,“容量”不会发生变化。 '长度'确实。 –

回答

1

使用.ToArray的名单,像这样:

list.ToArray(); 

对于反之亦然,你可以使用.ToList

1

还有就是,你可以随时换用手中有两张数组元素,而无需使用任何列表:

public static void Swap<T>(T[] array, int i, int j) 
{ 
    T temp = array[i]; 
    array[i] = array[j]; 
    array[j] = temp; 
}