Csharp/C#教程:使用随机类删除数组中的指定元素分享


使用随机类删除数组中的指定元素

class Check { public static void Main() { int[] arr1 = new int[] { 1, 2, 3 }; Console.WriteLine("The Number That Left Us Is"); Random rnd = new Random(); int r = rnd.Next(arr1.Length); int Left = (arr1[r]); Console.WriteLine(Left); } } 

如果生成2,我希望2被删除,剩下的我必须留下,应该是1和3.任何人都可以帮忙。 它可以在数组中完成。

数组不能重新resize,你设置它们永远是那么大。

“最佳”选项是使用List而不是int[]

 class Check { public static void Main() { List arr1 = Listint[] { 1, 2, 3 }; Console.WriteLine("The Number That Left Us Is"); Random rnd = new Random(); int r = rnd.Next(arr1.Length); int Left = (arr1[r]); arr1.RemoveAt(r); Console.WriteLine(Left); } } 

要实际创建一个更小的一个新数组将需要更多的代码。

 class Check { public static void Main() { int[] arr1 = int[] { 1, 2, 3 }; Console.WriteLine("The Number That Left Us Is"); Random rnd = new Random(); int r = rnd.Next(arr1.Length); int Left = (arr1[r]); int oldLength = arr1.Length; arrTmp = arr1; arr1 = new int[oldLength - 1]; Array.Copy(arrTmp, arr1, r); Array.Copy(arrTmp, r+1, arr1, r, oldLength - r - 1); Console.WriteLine(Left); } } 

你提到“你必须坚持使用数组”,将列表转换为数组非常容易

 class Check { public static void Main() { List arr1 = Listint[] { 1, 2, 3 }; Console.WriteLine("The Number That Left Us Is"); Random rnd = new Random(); int r = rnd.Next(arr1.Length); int Left = (arr1[r]); arr1.RemoveAt(r); Console.WriteLine(Left); SomeFunctionThatTakesAnArrayAsAnArgument(arr1.ToArray()); } } 

如果要使用List删除项目,则无法调整数组的大小。

但是,您可以创建一个新的。 如果你想保留除随机索引之外的所有项目:

 arr1 = arr1.Where((i, index) => index != r).ToArray(); 

使用列表,您可以使用RemoveAt ,这比创建数组更有效:

 var list = new List { 1, 2, 3 }; list.RemoveAt(r); 

数组无法在.NET中动态resize,因此您无法从数组中“删除”某个项目(您可以将其设置为0,但我认为这不是您想要的)。

尝试使用List

 List list = new List() { 1, 2, 3 }; Console.WriteLine("The Number That Left Us Is"); Random rnd = new Random(); int r = rnd.Next(list.Count); int Left = (list[r]); list.Remove(Left); Console.WriteLine(Left); 

尝试按照它从列表中删除项目并创建一个没有特定项目的新数组。

上述就是C#学习教程:使用随机类删除数组中的指定元素分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 static void Main(string[] args) { int[] arr1 = new int[] { 1, 2, 3 }; Console.WriteLine("The Number That Left Us Is"); Random rnd = new Random(); int r = rnd.Next(arr1.Length); // Create a new array except the item in the specific location arr1 = arr1.Except(new int[]{arr1[r]}).ToArray(); int Left = (arr1[r]); Console.WriteLine(Left); } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1005708.html

(0)
上一篇 2021年12月28日
下一篇 2021年12月28日

精彩推荐