以下是我的代码 我需要一个随机数组的单个字符串。
string[,] array = new string[4,3] { { "a1", "b1", "c1" }, {"a2", "b2", "c2" } ,
{ "a3", "b3", "c3" }, { "a4", "b4", "c4" } } ;
//string a =???
//string b =???
//string c =???
我需要的是a1,b1 c1或a2,b2,c2等......
任何想法都将受到赞赏..
谢谢, ARNAB
答案 0 :(得分:1)
正如我所理解的那样,你想要获取你随机获得的行的列。
为此,只需在行索引上使用Math.Random()
即可。在这种情况下数组[4]。
答案 1 :(得分:1)
我强烈建议您使用jagged array。在这种情况下,您可以使用此扩展方法:
private static readonly Random _generator = new Random();
public static T RandomItem<T>(this T[] array)
{
return array[_generator.Next(array.Length)];
}
像这样使用它:
string[][] array = new string[][] {
new string[] { "a1", "b1", "c1" },
new string[] { "a2", "b2", "c2" },
new string[] { "a3", "b3", "c3" },
new string[] { "a4", "b4", "c4" } };
string randomValue = array.RandomItem().RandomItem(); // b2 or c4 or ... etc.
一下子:
string[] randomValues = array.RandomItem(); // { "a3", "b3", "c3" } or ... etc.
或
string randomValues = string.Join(", ", array.RandomItem()); // a4, b4, c4
答案 2 :(得分:0)
<击> 这将根据字符串
//http://stackoverflow.com/questions/3150678/using-linq-with-2d-array-select-not-found
string[,] array = new string[4,3] { { "a1", "b1", "c1" }, {"a2", "b2", "c2" } ,
{ "a3", "b3", "c3" }, { "a4", "b4", "c4" } } ;
var query = from string item in array
select item;
var groupby = query.GroupBy(x => x[1]).ToArray();
var rand = new Random();
//Dump is an extension method from LinqPad
groupby[rand.Next(groupby.Length)].Dump();
这将输出(随机):
> a1,b1,c1
> a2,b2,c2
> a3,b3,c3
> a4,b4,c4
击> <击> 撞击>
LOL,矫枉过正,没读过数组已经“按分组”索引......