我有一个class
,其中包含array
秒class
,就像这样:
public class SimpayRecords
{
public int a;
public int b;
public int c;
public SimpayRecord[] records;
}
我有第三个class
,其中包含SimpayRecords
类。在第三个class
中,我想循环遍历array
并删除不需要的项目。像这样:
for (int i = 0; i < this.Records.Records.Length; i++)
{
if (this.Records.Records[i].Date < this.LastTime)
//remove TempRecords.Records[i]
}
我该怎么做?
答案 0 :(得分:1)
无法删除数组元素。你需要List。
请务必参考System.Collections.Generic
。
using System.Collections.Generic;
你的课就像。
public class SimpayRecords
{
public int a;
public int b;
public int c;
public List<SimpayRecord> records; // This is the List.
}
从列表中删除
for (int i = 0; i < this.Records.Records.Count; i++)
{
if (this.Records.Records[i].Date < this.LastTime)
this.Records.Records.RemoveAt(i--); // Removes the element at this index
}
因为List与普通数组不同。所以你必须了解List。如何创建它们以及如何使用它们。所以看看这些。
https://msdn.microsoft.com/en-us/library/6sh2ey19%28v=vs.110%29.aspx http://www.dotnetperls.com/list
答案 1 :(得分:1)
如果将新数组实例重新分配给this.Records.Records
并不是不可能的,那么您可以在LINQ中使用简单的WHERE
条件(将条件反转为>=
)来实现查询,像这样:
using System.Linq;
// ...
this.Records.Records = this.Records.Records.Where(r => r.Date >= this.LastTime).ToArray();
答案 2 :(得分:1)
如果您不想使用List来存储数据,可以使用Extension方法,如回答this question
所示public static class ArrayExtensions{
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;
}
}
然后您可以使用RemoveAt方法:
Foo[] bar = GetFoos();
bar = bar.RemoveAt(2);
希望这有帮助