[英]Two dimensional array slice in C#
我正在尋找在 C# 中對二維數組進行切片。
我有 double[2,2] 價格,想檢索這個數組的第二行。 我已經嘗試過價格 [1,],但我覺得它可能是別的東西。
提前致謝。
沒有直接的“切片”操作,但您可以像這樣定義擴展方法:
public static IEnumerable<T> SliceRow<T>(this T[,] array, int row)
{
for (var i = 0; i < array.GetLength(0); i++)
{
yield return array[i, row];
}
}
double[,] prices = ...;
double[] secondRow = prices.SliceRow(1).ToArray();
Enumerable.Range(0, 2)
.Select(x => prices[1,x])
.ToArray();
問題是如果你有一個鋸齒狀或多維數組......這里是如何從其中一個檢索值:
int[,] rectArray = new int[3,3]
{
{0,1,2}
{3,4,5}
{6,7,8}
};
int i = rectArray[2,2]; // i will be 8
int[][] jaggedArray = new int[3][3]
{
{0,1,2}
{3,4,5}
{6,7,8}
};
int i = jaggedArray[2][2]; //i will be 8
編輯:添加以解決切片部分...
要從其中一個數組中獲取一個 int 數組,您必須循環並檢索您所追求的值。 例如:
public IEnumerable<int> GetIntsFromArray(int[][] theArray) {
for(int i = 0; i<3; i++) {
yield return theArray[2][i]; // would return 6, 7 ,8
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.