【问题标题】:Jagged arrays in C#C#中的交错数组
【发布时间】:2010-05-31 08:29:16
【问题描述】:

我正在尝试将整数数组存储到锯齿状数组中:

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;

【问题讨论】:

  • 这里的映射是什么?每个 CustomerId 都有一个分数?
  • 是的,每个 customerid 都有一个分数
  • 我认为我从未见过这种故意用 C# 编写 C 代码的尝试;)

标签: c# jagged-arrays


【解决方案1】:

更好、更面向对象的方法是创建一个带有 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 属性,可以考虑将其设为只读。

【讨论】:

  • 我不认为每个客户都有一个分数列表 - 鉴于第二个 sn-p,我认为每个客户都有一个分数。
  • 是的,每个客户只有一个分数
  • 相应地更新了我的答案。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-21
      • 2012-02-18
      • 2014-03-26
      • 2021-08-02
      • 2019-03-25
      • 2013-08-12
      • 1970-01-01
      相关资源
      最近更新 更多