Reputation: 2354
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
Upvotes: 0
Views: 606
Reputation: 4445
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......
Upvotes: 0
Reputation: 9780
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.
Upvotes: 1
Reputation: 3889
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].
Upvotes: 1