簡體   English   中英

C#中的鋸齒狀數組

[英]Jagged arrays in C#

我試圖存儲到鋸齒數組中的整數數組:

while (dr5.Read())
{                                        
   customer_id[i] = int.Parse(dr5["customer_id"].ToString());
   i++;       
}

dr5是一個數據讀取器。 我將customer_id存儲在一個數組中,我也想將分數存儲在另一個數組中。 我想在while循環中有以下內容

int[] customer_id = { 1, 2 };
int[] score = { 3, 4};
int[][] final_array = { customer_id, score };

有人可以幫我嗎? 編輯:這是我嘗試過的。 沒有顯示任何值。

 customer_id =  new int[count];
 score = new int[count];
 int i = 0;
while (dr5.Read())
{ 
   customer_id[i] = int.Parse(dr5["customer_id"].ToString());
   score[i] = 32;
   i++;

}
 int[][] final = { customer_id, score };

return this.final;

更好的, 更面向對象的方法是創建一個具有Scores屬性的Customer類:

public class Customer
{
    public Customer()
    {
        this.Scores = new List<int>();
    }

    public IList<int> Scores { get; private set; }
}

由於事實證明每個客戶只有一個分數,因此更正確的客戶類別可能看起來像這樣:

public class Customer
{
    public int Score { get; set; }
}

如果不需要以后再更新它,則可以考慮將Score屬性設置為只讀。

您知道開始的尺寸嗎? 如果是這樣,您可以執行以下操作:

int[] customerIds = new int[size];
int[] scores = new int[size];
int index = 0;
while (dr5.Read())
{
    customerIds[index] = ...;
    scores[index] = ...;
    index++;
}
int[][] combined = { customerIds, scores };

但是,我建議您重新考慮。 聽起來您確實想將客戶ID與得分相關聯...因此創建一個類來這樣做。 然后,您可以執行以下操作:

List<Customer> customers = new List<Customer>();
while (dr5.Read())
{
    int customerId = ...;
    int score = ...;
    Customer customer = new Customer(customerId, score);
    customers.Add(customer);
}

作為使用數組的替代方法:

如果是一對一映射,則可以使用Dictionary這樣的臨時存儲:

var scores = new Dictionary<int, int>();
while (dr5.Read())  
{  
   scores.Add(int.Parse(dr5["customer_id"].ToString()), int.Parse(dr5["score"].ToString()));
}  

否則,您可以創建類客戶並從中列出。

暫無
暫無

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

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