如何在C#中从2D数组删除行和列? [英] How can I delete rows and columns from 2D array in C#?

查看:87
本文介绍了如何在C#中从2D数组删除行和列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从C#中的2D数组中删除特定的行和列?

How to delete a specific row and column from 2D array in C#?

int[,] array= {{1,2,3},{4,5,6},{7,8,9}};

让我说我要删除第i行和第i列(跳过它们)...对于nXn数组而不只是3x3,并将剩余的数组存储在新数组中……
因此输出将是:

lets say I want to delete row i and column i (skipping them) ... for nXn array not just 3x3 and store the remaining array in a new array... so the output would be:

{5,6},{8,9}


推荐答案

没有内置的方法可以执行以下操作:

There's no built-in way to do that, you can do it yourself:

 static void Main()
        {
            int[,] array = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
            var trim = TrimArray(0, 2, array);
        }


        public static int[,] TrimArray(int rowToRemove, int columnToRemove, int[,] originalArray)
        {
            int[,] result = new int[originalArray.GetLength(0) - 1, originalArray.GetLength(1) - 1];

            for (int i = 0, j = 0; i < originalArray.GetLength(0); i++)
            {
                if (i == rowToRemove)
                    continue;

                for (int k = 0, u = 0; k < originalArray.GetLength(1); k++)
                {
                    if (k == columnToRemove)
                        continue;

                    result[j, u] = originalArray[i, k];
                    u++;
                }
                j++;
            }

            return result;
        }

这篇关于如何在C#中从2D数组删除行和列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆