【问题标题】:Getting a random string from a multidimensional array从多维数组中获取随机字符串
【发布时间】:2013-08-13 16:16:46
【问题描述】:

以下是我的代码 我需要一个随机数组的单个字符串。

 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 等...

任何想法将不胜感激..

谢谢, 阿纳布

【问题讨论】:

标签: c# c#-4.0


【解决方案1】:

据我了解,您想获取随机获得的行的列。 为此,只需在行索引上使用Math.Random()。在本例中为数组[4]。

【讨论】:

  • 谢谢,随机 rnd = new Random(); int i = rnd.Next(1, 4);字符串 a= 数组[i, 0];...
【解决方案2】:

我强烈建议使用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

Why do i recommend is explained here.

【讨论】:

    【解决方案3】:

    这将根据字符串的第二个字符对字符串进行分组

    //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
    

    大声笑,矫枉过正,没有读取数组已经被索引“分组”了......

    http://www.linqpad.net/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-09
      • 1970-01-01
      • 2021-03-06
      • 2011-02-18
      • 1970-01-01
      相关资源
      最近更新 更多