views:

96

answers:

3

Hello! Im trying to store to array of ints in a jagged array:

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

dr5 is a datareader. I am storing the customer_id in an array, i also want to store scores in another array. I want to have something like below within the while loop

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

Can anyone help me please ? EDIT: this is what i have tried. No values are being displayed.

 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;
+3  A: 

A better, more object-oriented approach would be to create a Customer class with a Scores property:

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

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

Since it turns out that there is only one score per customer, a more correct Customer class might look like this:

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

You might consider making the Score property read-only if you don't need to be able to update it afterwards.

Mark Seemann
I don't think each customer has a list of scores - given the second snippet, I think there's one score per customer.
Jon Skeet
Yes there is one score per customer
chupinette
Updated my answer accordingly.
Mark Seemann
+1  A: 

Do you know the size to start with? If so, you could do:

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

However, I would advise you to rethink. It sounds like you really want to associate a customer ID with a score... so create a class to do so. Then you can do:

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

As an alternative idea of using arrays:

If it is a one to one mapping you can use Dictionary for temporary storage like this:

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

Else you can create a class customer and make a list out of it.

Veer