0

以下は、ランダム配列の個々の文字列が必要な私のコードです。

 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などです...

どんなアイデアでも大歓迎です..

ありがとう、アルナブ

4

3 に答える 3

1

私が理解しているように、ランダムに取得した行の列を取得したいと考えています。このためMath.Random()には、行インデックスで使用するだけです。この場合、配列[4]。

于 2013-08-12T11:26:48.753 に答える
1

ジャグ配列を使用することを強くお勧めします。この場合、次の拡張メソッドを使用できます。

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

おすすめする理由はこちらで説明しています

于 2013-08-12T11:37:26.203 に答える
0

これは、文字列の 2 番目の文字に基づいて文字列をグループ化します

//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、やり過ぎ、配列がインデックスによって既に「グループ化」されていることを読み取らなかった......

http://www.linqpad.net/

于 2013-08-12T11:45:53.510 に答える