如何使用LINQ创建和显示随机整数2-D数组? 请帮帮我! 我创建随机2-D数组,但不是LINQ。
Random rnd = new Random();
int[,] matrix = new int[rows, columns];
for (int i = 0; i < matrix.GetLength(0); i++)
for (int j = 0; j < matrix.GetLength(1); j++)
matrix[i, j] = rnd.Next(-100,100);
Console.WriteLine("Array:");
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
Console.Write("{0}\t", matrix[i, j]);
Console.WriteLine();
}
答案 0 :(得分:2)
使用linq创建一个10x10阵列:
var r = new Random();
var result = Enumerable.Range(0, 10).Select(x =>
Enumerable.Range(0, 10).Select(y => r.Next()).ToArray())
.ToArray();
答案 1 :(得分:0)
如果你真的想要过度复杂化:
static void Main(string[] args)
{
int rows = 10;
int columns = 10;
int[,] matrix = new int[rows, columns];
Random rnd = new Random();
Enumerable.Range(0, rows)
.ToList()
.ForEach(row => Enumerable.Range(0, columns)
.ToList()
.ForEach(column =>
{
matrix[row, column] = rnd.Next(-100, 100);
Console.Write(column == columns ? Environment.NewLine + matrix[row, column].ToString() + "\t" : matrix[row, column].ToString() + "\t");
}));
Console.ReadKey();
}