我在C#中有一個二維數組。後來我想訪問數組的元素 - 不僅是一個,而是整行。一次訪問數組中的整行
int[,] example = { { 1, 2, 3 }, { 4, 5, 6 }, {7, 8, 9} }
list<int> extract = ??? row1 of example ???
什麼是最快的方法來做到這一點?
我在C#中有一個二維數組。後來我想訪問數組的元素 - 不僅是一個,而是整行。一次訪問數組中的整行
int[,] example = { { 1, 2, 3 }, { 4, 5, 6 }, {7, 8, 9} }
list<int> extract = ??? row1 of example ???
什麼是最快的方法來做到這一點?
使用LINQ可以實現這樣的:
List<int> extract = Enumerable.Range(0, example.GetLength(1))
.Select(x => example[0,x])
.ToList();
你真的沒有比其他任何選擇通過所有列的迭代,看着每一行中的值:
public static IEnumerable<T> GetRow<T>(this T[,] array, int row)
{
for (int i = 0; i < array.GetLength(1); i++)
yield return array[row, i];
}
做到這一點的一種方法可能不是製作二維數組(這可能是內部一維數組,訪問像array[x,y] = __array[x + width * y]
但使用數組數組(我不會寫出在C#中完成此操作的確切語法,因爲我不是C#大約5年,也許是這樣如int[][] arr = new int[3]; arr[0] = new int[3]; arr[1] = new int[3]; arr[2] = new int[3]
)。
然後你就可以使用arr[n]
最快的方式做到這一點很可能是,如果你可以使用一個數組,而不是結果的列表,以解決整個列,使用Buffer.BlockCopy()
像這樣:
using System;
using System.Linq;
namespace Demo
{
internal class Program
{
private static void Main()
{
int[,] example =
{
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12},
{13, 14, 15, 16},
{17, 18, 19, 20},
};
int sourceColumns = example.GetUpperBound(0);
int[] row1 = new int[sourceColumns];
int requiredRow = 3;
int sourceOffset = requiredRow * sourceColumns * sizeof(int);
int sourceWidthBytes = sourceColumns*sizeof (int);
Buffer.BlockCopy(example, sourceOffset, row1, 0, sourceWidthBytes);
// Now row1 contains 13, 14, 15, 16. Prove it by writing to display:
Console.WriteLine(string.Join(", ", row1));
// If you really must have a List<int>
// (but this will likely make it much slower than just
// adding items to the list on an element-by-element basis):
var list = new List<int>(row1);
// Do something with list.
}
}
}
但是,不要對什麼更快做出任何假設。
做一些時間與Stopwatch
發佈版本確定。
如果您正在尋找_fastest way_,請嘗試所有可以解決您的問題並對其進行比較的方法。 – 2014-09-25 13:55:07