[英]Remove array from multidimension array inside jagged arrays
我有一個帶有多維數組的鋸齒狀數組,並且想要刪除多維數組中的一個數組。 我的代碼是:
int[][,] arr = new int[4][,];
arr[0] = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 5, 6, 7 }, { 8, 9, 10 } };
arr[1] = new int[,] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } };
arr[2] = new int[,] { { 1, 2, 3, 4, 5 }, { 5, 6, 7, 8, 9 }, { 10, 11, 12, 13, 14 },{ 15, 16, 17, 18, 19 } };
arr[3] = new int[,] { { 1, 2, 3, 4, 5, 6}, { 5, 6, 7, 8, 9, 10}, { 11, 12, 13, 14, 15, 16 }, { 17, 18, 19, 20, 21, 22 } };
int[,] removeArray = { { 1, 2, 3 } };
我嘗試使用 linq 從 arr[0] 中刪除 {1,2,3}:
arr = arr.Where((val,i) => i != 0).ToArray();
但這會刪除整個 arr[0] 行。 有誰知道我如何使用 linq 刪除 {1,2,3}?
與交錯數組不同,多維數組不包含數組:
int[][] jagged = new int[][] {
new[] { 1, 2, 3}, // <- this is an array
new[] { 4, 5},
};
int[,] array2D = new int[,] {
{1, 2, 3}, // <- not an array
{4, 5, 6}, // <- not an array
};
因此,如果您想從2d array中“刪除”行,則必須重新創建它; 像這樣的東西:
private static T[,] RemoveRows<T>(T[,] source, T[] row) {
if (row.Length != source.GetLongLength(1))
return source;
List<int> keepRows = new();
for (int r = 0; r < source.GetLength(0); ++r)
for (int c = 0; c < row.Length; ++c)
if (!object.Equals(source[r, c], row[c])) {
keepRows.Add(r);
break;
}
if (keepRows.Count == source.Length)
return source;
T[,] result = new T[keepRows.Count, source.GetLength(1)];
for (int r = 0; r < keepRows.Count; ++r)
for (int c = 0; c < result.GetLength(1); ++c)
result[r, c] = source[keepRows[r], c];
return result;
}
接着
// we remove row; let it be 1d array, not 2d one
int[] removeArray = { 1, 2, 3 };
arr = arr
.Select(array => RemoveRows(array, removeArray))
.ToArray();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.