【问题标题】:System.IndexOutOfRangeException when forming list形成列表时出现 System.IndexOutOfRangeException
【发布时间】:2012-09-30 23:22:56
【问题描述】:

我正在尝试借助看起来像这样的多维数组来形成一个列表。

[validatorKey][counter]
1453          10
1231          12
6431          7
1246          1
1458          2

但是,我无法应付。顺便说一句,这是我的方法。并且数组大小应该在方法的最后增加。我知道我应该使用 Array.Resize(ref array, 2);但由于我的数组是多维的,在这种情况下应该是什么合适的方法。

private int AracaAitSeferSayisiDondur(int pValidatorKey)
{
     int iSeferSayisi = 0;
     int[,] iSeferListesi = (int[,])ViewState["SeferListesi"];
     if (iSeferListesi == null)
     iSeferListesi = new int[1,1];

     bool aynisiVarmi = false;

     for (int i = 0; i < iSeferListesi.Length; i++)
     {
        if (iSeferListesi[i,0] == pValidatorKey)
        {
           aynisiVarmi = true;
           iSeferListesi[i,1]++;
           iSeferSayisi = iSeferListesi[i,1]++;
           break;
        }
     }
     if (!aynisiVarmi)
     {
        int arrayLength = iSeferListesi.Length;
        iSeferListesi[arrayLength--, 0] = pValidatorKey;
        iSeferListesi[arrayLength--, 1] = 1;
        //IN THIS PART ARRAY SIZE SHOULD BE INCREASED
        iSeferSayisi = iSeferListesi[arrayLength--, 1];
     }
     ViewState["SeferListesi"] = iSeferListesi;
     return iSeferSayisi;
}

【问题讨论】:

  • 数组增长得不是很好。使用List&lt;&gt;Dictionary&lt;&gt;
  • 有一个问题涉及调整多维数组here。我同意@Henk,但列表或字典可能比数组更适合您的需求。
  • @ŞafakGür,谢谢兄弟。

标签: c#


【解决方案1】:

我认为你需要类似的东西:

// not tested
private int AracaAitSeferSayisiDondur(int pValidatorKey)
{
    var iSeferListesi = (Dictionary<int,int>)ViewState["SeferListesi"];
     if (iSeferListesi == null)
        iSeferListesi = new Dictionary<int,int>;

     int iSeferSayisi;

    if ( iSeferListesi.TryGetValue(pValidatorKey, out iSeferSayisi)
    {
       iSeferSayisi += 1;
       iSeferListesi[pValidatorKey] = iSeferSayisi;
       iSeferSayisi += 1;  // is this OK ??
    }
    else
    {
       iSeferSayisi = 1;
       iSeferListesi[pValidatorKey] = iSeferSayisi;
    }

    ViewState["SeferListesi"] = iSeferListesi;
    return iSeferSayisi;
}

iSeferListesi 的双倍增量(源自您的代码)可能不是您想要的,没有它,if/else 逻辑会变得更加简单。

【讨论】:

    【解决方案2】:

    Length 属性返回数组中元素的总数。

    使用GetLength(dimension) method 获取维度的大小:

    for (int i = 0; i < iSeferListesi.GetLength(0); i++)
    

    和:

    int arrayLength = iSeferListesi.GetLength(0);
    

    【讨论】:

    • 但我在这部分得到了错误。 iSeferListesi[arrayLength--, 0] = pValidatorKey;
    • @MehmetBudak:那里也一样:int arrayLength = iSeferListesi.GetLength(0);
    猜你喜欢
    • 2018-03-15
    • 1970-01-01
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    相关资源
    最近更新 更多