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

4
  • 1
    @Jayram No, he wants to take an entire row of a 2dim array. It's different. Commented Aug 12, 2013 at 11:23
  • 1
    possible duplicate of How to copy a row of values from a 2D array into a 1D array? Commented Aug 12, 2013 at 11:24
  • thanks for pointing..i removed that :) Commented Aug 12, 2013 at 11:24
  • Thanks all, Sorry for not detailing the requirement Commented Aug 13, 2013 at 5:06

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Random rnd = new Random(); int i = rnd.Next(1, 4); string a= array[i, 0];...
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.

Comments

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.