0

我试图存储到锯齿状数组中的整数数组:

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;
4

3 回答 3

4

更好、更面向对象的方法是创建一个带有 Scores 属性的 Customer 类:

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

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

由于事实证明每个客户只有一个分数,因此更正确的 Customer 类可能如下所示:

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

如果您以后不需要更新它,您可以考虑将 Score 属性设为只读。

于 2010-05-31T08:37:19.183 回答
1

你知道开始的尺寸吗?如果是这样,你可以这样做:

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);
}
于 2010-05-31T08:39:50.097 回答
0

作为使用数组的另一种想法:

如果它是一对一的映射,您可以使用 Dictionary 进行临时存储,如下所示:

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

否则,您可以创建一个类客户并从中列出。

于 2010-05-31T08:44:52.863 回答