我正在尝试使此代码尽可能高效,什么是最好,最正确的方法?另外,我需要找到每一列和每一行的MIN和MAX值,并在特定的行和列旁边显示这些值。
代码:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
Random rand = new Random();
int ri, ki;
int i, j;
int max = 1;
int min = 0;
int rndnumber = rand.Next(64, 128);
int[,] array = new int[9, 4]; // Izveido array 9x4 (rin x kol)
for (i = 0; i < 9; i++) //
{
for (j = 0; j < 4; j++)
array[i, j] = rand.Next(1, 100 + 1);
}
for (i = 0; i < 9; i++) //
{
for (j = 0; j < 4; j++)
{
Console.Write("|\t{0}\t ", array[i, j]); // /t - tab
}
Console.WriteLine("\n"); // new line
}
for (i = 0; i < 9; i++) //
{
for (j = 0; j < 4; j++)
if (max < array[i, j]) // Aprekina max
{
max = array[i, j];
}
}
Console.WriteLine("Maksimalais sk tabula: {0}", max);
Console.WriteLine("Min sk tabula: {0}", min);
//rndnumber = rand.Next();
//Console.WriteLine("Hello World {0}", rndnumber);
Console.ReadKey();
/*
Izveidot ka zem katras rindas un kol ir min un max skaitlis
*/
}
}
答案 0 :(得分:2)
如果将多维数组变成IEnumerable
,则可以在其上使用Linq:
// Order and use Cast<int>() to get an ordered IEnumerable<int>,
var orderedAscending = from x in array.Cast<int>()
orderby x
select x;
// Use linq First() & Last() to get min and max.
var min = orderedAscending.First();
var max = orderedAscending.Last();