-2

所以我在一个数组中有一组变量,我想从每个(比如说)第 4 个索引中收集数据。例如,如果我有数组 all[],它[0]->id [1]->field1 [2]->field2在 a[3]->linebreak和之后有数据,在另一组 and 之后[4]->id [5]->field1[6]->field2 [7]->linebreak依此类推。现在我想创建一个名为 id[] 的数组(或列表),其中包含所有 id 和一个field1[]包含所有字段的数组。我怎么能这样做?

4

2 回答 2

5

您可以对每个数组元素的索引应用模 4 来确定其在其四组中的位置。ID 将位于位置 0;字段将位于位置 1 和 2。

int[] ids = all.Where((_, i) => i % 4 == 0).ToArray();
int[] fields = all.Where((_, i) => i % 4 == 1 || i % 4 == 2).ToArray();
于 2015-08-21T19:58:36.247 回答
1

您可能会发现将数据存储在对象中更容易......

public class DataObject {

    public DataObject() {}
    public DataObject(string[] fields) {   
        // this is an example.  construct a .ctor that is sane for your data.
        // TODO:  Add array bounds checking and data sanity checks
        this.ID = fields[0];
        this.Field1 = fields[1];
        this.Field2 = fields[2];
    }

    public string ID {get; set;}

    public string Field1 {get; set;}

    public string Field2 {get; set;}
}

然后,您将存储一个数组或类似数组的结构DataObject

于 2015-08-21T20:12:23.927 回答