我有以下锯齿状的“dists”数组
int[][] dists = new int[][]
{
new int[]{0,2,3,5,2},
new int[]{2,0,1,3,5},
new int[]{3,1,0,4,4},
new int[]{5,3,4,0,2},
new int[]{2,5,4,2,0}
};
现在,当我从原始数组finalDists
中删除第3行和第3列时,我想创建另一个名为dists
的锯齿状数组。我的意思是我希望最终有以下锯齿状数组:
int[][] finalDists = new int[][]
{
new int[]{0,2,5,2},
new int[]{2,0,3,5},
new int[]{5,3,0,2},
new int[]{2,5,2,0}
};
在感谢你的帮助之前,我很困惑如何处理这个问题
答案 0 :(得分:7)
int[][] finalDists = dists.Where((arr, i)=>i!=2) //skip row#3
.Select(arr=>arr.Where((item,i)=>i!=2) //skip col#3
.ToArray())
.ToArray();
答案 1 :(得分:1)
不是很优化但是:
public static T[] RemoveRow<T>(T[] array, int row)
{
T[] array2 = new T[array.Length - 1];
Array.Copy(array, 0, array2, 0, row);
Array.Copy(array, row + 1, array2, row, array2.Length - row);
return array2;
}
public static T[][] RemoveColumn<T>(T[][] array, int column)
{
T[][] array2 = new T[array.Length][];
for (int i = 0; i < array.Length; i++)
{
array2[i] = RemoveRow(array[i], column);
}
return array2;
}
和
int[][] dists = new int[][]
{
new int[]{0,2,3,5,2},
new int[]{2,0,1,3,5},
new int[]{3,1,0,4,4},
new int[]{5,3,4,0,2},
new int[]{2,5,4,2,0}
};
int[][] dists2 = RemoveColumn(RemoveRow(dists, 2), 2);
请注意,您要删除第三个行和第三个列,但它们的索引是 2 ,因为.NET数组为0基于索引!