当前位置:编程学习 > C#/ASP.NET >>

c#怎么从数组随机取出一个,并且把他删除,避免重复

比如int [,]arry; arry=new int[,]{{2,2},{2,2},{3,3}};
我想随机取出里面的如{2,2}并且把他删除,避免下次又选中 --------------------编程问答-------------------- 要么你重新new一个数组,将剩下的拷贝过去,要么转为List,删除,然后在ToArray,或用LInQ --------------------编程问答-------------------- 楼主想太多了,数组没那么灵活,用list吧 --------------------编程问答-------------------- lz还是用交错数组吧 --------------------编程问答-------------------- 用list吧 --------------------编程问答-------------------- 2维数组的大小是不能改变的,变通的方法:
		int[,] array = new int[,] { { 1, 1 }, { 2, 2 }, { 3, 3 }, { 4, 4 }, { 5, 5 } };
int index = new Random().Next(array.GetLength(0));
array[index, 0] = array[index, 1] = int.MinValue;
var temp = array.Cast<int>().Where(x => x != int.MinValue);
array = new int[temp.Count() / 2, 2];
for (int i = 0; i < array.GetLength(0); i++)
{
array[i, 0] = temp.ElementAt(i * 2);
array[i, 1] = temp.ElementAt(i * 2 + 1);
}
//输出
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
Response.Write(array[i, j] + " ");
Response.Write("<br/>");
}
--------------------编程问答-------------------- 建议用交错数组,比较方便:
		int[][] array = new int[5][];
for (int i = 0; i < array.Length; i++)//生一个{0,0},{1,1},{2,2},{3,3},{4,4}的交错数组
array[i] = new int[2] { i, i };
int index = new Random().Next(array.Length);
array = array.Where((x, y) => y != index).ToArray();
foreach (int[] v in array)
Response.Write(v[0] + " " + v[1] + "<br/>");
--------------------编程问答-------------------- 或者用泛型列表List<T>也很方便,这个本身支持增删:
		List<int[]> array = new List<int[]>();
for (int i = 0; i < 5; i++)//生成一个生一个包含{0,0},{1,1},{2,2},{3,3},{4,4}的泛型列表
array.Add(new int[] { i, i });
int index = new Random().Next(array.Count);
array.RemoveAt(index);
foreach (int[] v in array)
Response.Write(v[0] + " " + v[1] + "<br/>");
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,