如何从c#中删除2d数组中的行?

时间:2011-11-03 09:38:41

标签: c#

  

可能重复:
  Delete row of 2D string array in C#

我有一个2d字符串数组,我想从数组中删除指定的行。

5 个答案:

答案 0 :(得分:4)

string[] a = new string[] { "a", "b" }; //dummy string array
int deleteIndex = 1; //we want to "delete" element in position 1 of string
a = a.ToList().Where(i => !a.ElementAt(deleteIndex).Equals(i)).ToArray();

脏但是给出了预期的结果(foreach通过数组来测试它)

编辑错过了“2d阵列”细节,这里是正确的代码

    string[][] a = new string[][] { 
        new string[] { "a", "b" } /*1st row*/, 
        new string[] { "c", "d" } /*2nd row*/, 
        new string[] { "e", "f" } /*3rd row*/
    };
    int rowToRemove = 1; //we want to get rid of row {"c","d"}
    //a = a.ToList().Where(i => !i.Equals(a.ElementAt(rowToRemove))).ToArray(); //a now has 2 rows, 1st and 3rd only.
    a = a.Where((el, i) => i != rowToRemove).ToArray(); // even better way to do it maybe

代码已更新

答案 1 :(得分:1)

如上所述,你无法从数组中删除。

如果您需要经常删除行,可能会从使用2d数组更改为包含字符串数组的列表。这样,您就可以使用列出实现的remove方法。

答案 2 :(得分:1)

好的,所以我说你不能“删除”它们。那仍然是真的。您必须创建一个新的数组实例,并为要保留的项目留出足够的空间并将其复制。

如果这是一个锯齿状数组,那么在这里使用LINQ可以简化这一过程。

string[][] arr2d =
{
    new[] { "foo" },
    new[] { "bar", "baz" },
    new[] { "qux" },
};

// to remove the second row (index 1)
int rowToRemove = 1;
string[][] newArr2d = arr2d
    .Where((arr, index) => index != rowToRemove)
    .ToArray();

// to remove multiple rows (by index)
HashSet<int> rowsToRemove = new HashSet<int> { 0, 2 };
string[][] newArr2d = arr2d
    .Where((arr, index) => !rowsToRemove.Contains(index))
    .ToArray();

您可以使用其他LINQ方法更轻松地删除行范围(例如Skip()Take()TakeWhile()等。)

如果这是一个真正的二维(或其他多维)数组,那么你将无法在这里使用LINQ,并且必须手动完成它并且它会更加复杂。这仍然适用于锯齿状阵列。

string[,] arr2d =
{
    { "foo", null },
    { "bar", "baz" },
    { "qux", null },
};

// to remove the second row (index 1)
int rowToRemove = 1;
int rowsToKeep = arr2d.GetLength(0) - 1;
string[,] newArr2d = new string[rowsToKeep, arr2d.GetLength(1)];
int currentRow = 0;
for (int i = 0; i < arr2d.GetLength(0); i++)
{
    if (i != rowToRemove)
    {
        for (int j = 0; j < arr2d.GetLength(1); j++)
        {
            newArr2d[currentRow, j] = arr2d[i, j];
        }
        currentRow++;
    }
}

// to remove multiple rows (by index)
HashSet<int> rowsToRemove = new HashSet<int> { 0, 2 };
int rowsToKeep = arr2d.GetLength(0) - rowsToRemove.Count;
string[,] newArr2d = new string[rowsToKeep, arr2d.GetLength(1)];
int currentRow = 0;
for (int i = 0; i < arr2d.GetLength(0); i++)
{
    if (!rowsToRemove.Contains(i))
    {
        for (int j = 0; j < arr2d.GetLength(1); j++)
        {
            newArr2d[currentRow, j] = arr2d[i, j];
        }
        currentRow++;
    }
}

答案 3 :(得分:0)

您可以使用List或ArrayList类代替数组。使用它,您可以根据您的要求动态添加元素并删除。数组是固定大小的,不能动态操作。

答案 4 :(得分:0)

最好的方法是使用List<Type>!这些项目按照添加到列表中的方式排序,并且每个项目都可以删除。

像这样:

var items = new List<string>;
items.Add("One");
items.Add("Two");
items.RemoveAt(1);