簡體   English   中英

組織數組 C#

[英]Organizing arrays c#

所以我在一個數組中有一組變量,我想從每個(假設)第 4 個索引中收集數據。 例如,如果我有數組 all[],它在[0]->id [1]->field1 [2]->field2[3]->linebreak和另一組[4]->id [5]->field1[6]->field2 [7]->linebreak等等。 現在我想創建一個名為 id[] 的數組(或列表),其中包含所有 id 和一個field1[] ,其中包含所有字段。 我怎么能這樣做?

您可以對每個數組元素的索引應用模 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();

您可能會發現將數據存儲在對象中更容易...

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的數組或類似數組的結構。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM