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
}
}
}
是否有等效的方法为列表类型与数组只是工作,而不是使用一个名单,然后转换回阵列?我应该使用不同的系统库参考吗?
不知道你在做什么......不是很清楚。但从列表到数组,然后你有'.ToList()'和'ToArray()' –
你错误'input.Length'与'input.Capacity'。一般情况下,当物品从列表中删除时,“容量”不会发生变化。 '长度'确实。 –