[英]how to remove a row from an 2-D Array
我遇到一个我不知道如何解决的问题。 我创建了一个包含日期和价格的二维数组。我想删除日期时间在两个日期之间的行。下面的示例,我想删除第三行。
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; }
}
然后,将它们存储在列表中,以便您可以使用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();
它将选择没有空,空或空格日期项的数据,并将它们放置在新数组中。
如果您不愿意使用像2D这样的非List数组,可以尝试以下操作:
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
您的解决方法不是最好的。 您应该创建一个助手类:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.