移除类数组的成员

本文关键字:成员 数组 | 更新日期: 2023-09-27 18:02:12

我有一个class,它包含第二个classarray,就像这样:

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]
}

我该怎么做?

移除类数组的成员

如果不想使用List来存储数据,可以使用Extension方法,如问题的答案

所示
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);

希望能有所帮助

如果将新的数组实例重新分配给this.Records.Records不是不可能的,您可以在LINQ查询中使用简单的WHERE条件(将您的条件逆转为>=)来完成,如下所示:

using System.Linq;
// ...
this.Records.Records = this.Records.Records.Where(r => r.Date >= this.LastTime).ToArray();

不能删除数组元素。你需要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.aspxhttp://www.dotnetperls.com/list