在 C# 中从 DataRow[] 中删除行

Deleting row from DataRow[] in C#

我有一个包含 5 行的数据行数组 DataRow[] drRequest。 然后我使用 foreach 迭代每一行并使用

删除行
foreach (DataRow dr in drRequest) 
{
    dr.Delete();

但之后 drRequest.Length 返回 5 而不是 0。

我不能使用 Datatable ,我需要使用 DataRow[]

DataRow.Delete doesn't remove this row from the DataTable. It just marks this row as "will be deleted from the datasource if you use a DataAdapter and call dataAdapter.Update". If you want to remove it use Remove:

foreach (DataRow dr in drRequest) 
{
    dr.Table.Rows.Remove(dr);
}

如果 drRequest 确实是一个 DataRow[],那么它 总是 有长度(无论它的开头是什么)。数组 永远不会改变长度 。绝不。您可以 null 从中获取一个值,但是...稍后查看该数组的任何其他代码可能都不会期望该值。这只是数组 .

的一个特征

可能考虑另一种数据结构。例如,您 可以 List<T> 中删除内容。但请注意,这在幕后涉及洗牌。如果您有选择地删除内容,那么 list.RemoveAll(x => {return true to remove, false to keep}); 知道如何以最佳方式执行此操作。