Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

C#如何随机选一个数组

int[,] pix_arr = new int[4, 2] { { 448, 292 }, { 1, 2 }, { 2, 4 }, { 3, 6 } };
在C#中,如何随机从上面二维数组中选一个一维的。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

简单点儿就生成个 Random,范围从 0 到数组长度减 1。

using System;

int[,] pix_arr = new int[4, 2] { { 448, 292 }, { 1, 2 }, { 2, 4 }, { 3, 6 } };
Random rand = new Random();
int i = rand.Next(0, pix_arr.Length); // 容错性要好的话注意判断一下长度为 0 的情况
var result = pix_arr[i];

要不就用 Linq,先随机排序,再取第一个。

using System;
using System.Linq;

int[,] pix_arr = new int[4, 2] { { 448, 292 }, { 1, 2 }, { 2, 4 }, { 3, 6 } };
var result = pix_arr.OrderBy(e => Guid.NewGuid()).FirstOrDefault();

P.S. 手头没 VS,徒手写的代码,可能有错误,能看明白就行了。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...