形成列表时System.IndexOutOfRangeException

时间:2012-09-30 12:17:33

标签: c#

我试图在多维数组的帮助下形成一个列表,看起来应该是这样的。

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

2 个答案:

答案 0 :(得分:1)

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

使用GetLength(dimension) method获取尺寸的大小:

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

int arrayLength = iSeferListesi.GetLength(0);

答案 1 :(得分: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逻辑变得更简单。

相关问题