如何从二维数组中删除一行
本文关键字:一行 删除 二维数组 | 更新日期: 2023-09-27 18:03:11
我遇到了一个不知道如何解决的问题。我创建了一个包含日期和价格的二维数组。我想删除datetime介于两个日期之间的行。在下面的例子中,我想删除第三行。
Date Price
01/07 10
02/07 20
Empty 30
03/07 40
这是我的代码:(我不知道为什么它工作)
for (int i=0;i<row.length;i++)
{
for (int j=0;j<col.length;j++)
{
if (Array[row,0]=" ")
{
Array[row,j]=Array[row+1,j];
i++
}
}
}
如果我是你,我会创建一个对象,并将Date和Price作为属性存储。
例如:public class DateAndPrice //let this name be whatever you want
{
public DateTime Date { get; set; }
public int Price { get; set; }
}
然后,将它们存储在List中,以便您可以使用remove方法轻松地删除它们。
List<DateAndPrice> list = new List<DateAndPrice>();
如果你不喜欢使用数组,你可以使用Linq查询来过滤掉结果并返回一个新的数组:
var data = new[] {
new { Date = "01/07", Price = 10 },
new { Date = "02/07", Price = 20 },
new { Date = "", Price = 30 },
new { Date = "03/07", Price = 40 }
};
var noBlanks = (from d in data
where !string.IsNullOrWhiteSpace(d.Date)
select d).ToArray();
它将选择没有空、null或空白日期项的数据,并将它们放在一个新数组中。
如果你决定使用非list类型的2D数组,你可以尝试以下方法:
string[,] array =
{
{ "01/07", "10" },
{ "02/07", "20" },
{ String.Empty, "30" },
{ "03/07", "40" },
};
array = RemoveEmptyDates(array);
for (int i = 0; i <= array.GetUpperBound(0); i++)
{
for (int j = 0; j <= array.GetUpperBound(1); j++)
{
Console.Write("{0} 't", array[i, j]);
}
Console.WriteLine();
}
RemoveEmptyDates看起来像:
public static string[,] RemoveEmptyDates(string[,] array)
{
// Find how many rows have an empty date
int rowsToRemove = 0;
for (int i = 0; i <= array.GetUpperBound(0); i++)
{
if (string.IsNullOrEmpty(array[i, 0]))
{
rowsToRemove++;
}
}
// Reinitialize an array minus the number of empty date rows
string[,] results = new string[array.GetUpperBound(0) + 1 - rowsToRemove, array.GetUpperBound(1) + 1];
int row = 0;
for (int i = 0; i <= array.GetUpperBound(0); i++)
{
int col = 0;
if (!string.IsNullOrEmpty(array[i, 0]))
{
for (int j = 0; j <= array.GetUpperBound(1); j++)
{
results[row, col] = array[i, j];
col++;
}
row++;
}
}
return results;
}
结果:
01/07 10
02/07 20
03/07 40
你的方法不是最好的。您应该创建一个helper类:
public class DatePrice
{
public DateTime Date { get; set; }
public decimal Price { get; set; }
}
然后创建集合类:
var prices = new List<DatePrice>();
然后你可以像这样添加数据:
prices.Add(new DatePrice() { Date = DateTime.Now, Price = 10m });
你可以很容易地删除一个基于索引的项目,像这样:
prices.RemoveAt(2);
如果确实必须使用数组,则需要一个扩展方法,例如这样删除一个项(从这里复制):
public static T[] RemoveAt<T>(this T[] source, int index)
{
T[] dest = new T[source.Length - 1];
if( index > 0 )
Array.Copy(source, 0, dest, 0, index);
if( index < source.Length - 1 )
Array.Copy(source, index + 1, dest, index, source.Length - index - 1);
return dest;
}
对于二维数组,使用:
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; // 2nd row
a = a.Where((el, i) => i != rowToRemove).ToArray();