0

The following is my code I need a random array's individual strings.

 string[,] array = new string[4,3]  { { "a1", "b1", "c1" }, {"a2", "b2", "c2" } , 
                                  { "a3", "b3", "c3" }, { "a4", "b4", "c4" } } ;

//string a =???
//string b =???
//string c =???

What I need is either a1, b1 c1 OR a2,b2,c2 etc...

Any ideas will be appreciated..

Thanks, Arnab

xanatos
  • 109,618
  • 12
  • 197
  • 280
Arnab
  • 2,324
  • 6
  • 36
  • 60

3 Answers3

1

As I have understood it, you want to fetch the columns of the row which you get randomly. For this, just use Math.Random() on the row index. In this case array[4].

Vivek Jain
  • 3,811
  • 6
  • 30
  • 47
1

I strongly recommend on using the jagged array. In the case, you might use this extension method:

private static readonly Random _generator = new Random();

public static T RandomItem<T>(this T[] array)
{
    return array[_generator.Next(array.Length)];
}

Using it like this:

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.

All at once:

string[] randomValues = array.RandomItem(); // { "a3", "b3", "c3" } or ... etc.

or

string randomValues = string.Join(", ", array.RandomItem()); // a4, b4, c4

Why do i recommend is explained here.

Community
  • 1
  • 1
AgentFire
  • 8,944
  • 8
  • 43
  • 90
0

this will group the strings based on the second char of string

//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();

This will output (Randomly):

> a1,b1,c1

> a2,b2,c2

> a3,b3,c3

> a4,b4,c4

LOL, overkill, Didn't read the array was already "grouped by" the index......

http://www.linqpad.net/

jjchiw
  • 4,375
  • 1
  • 29
  • 30