如何在C#中向集合对象添加值?

时间:2019-06-16 21:22:40

标签: c# generic-programming

如何在C#中向集合对象添加值?

我正在尝试将按递增顺序的值列表添加到集合对象。

示例语法:-

    Source Data

FirstName   LastName    Department  Salary
-------------------------------------------------------
John        Boone       Developer   100
Albert      Post        Manager     500
Benjamin    Nayyar      Developer   100


public class MyGroup
{
        public int RowIndex { get; set; } // Row Index
        public int ColumnIndex { get; set; } // Column Index
        public object ColumnValue { get; set; } // Column Value
}


class A
{
List<MyGroup> objMyGrp = new List<MyGroup>();
int iGrpCount = 0; 

 objMyGrp[iGrpCount].RowIndex = excelCell.RowIndex;
 objMyGrp[iGrpCount].ColumnIndex = excelCell.ColumnIndex;
 objMyGrp[iGrpCount].ColumnValue = excelCell.Value.ToString();

}

iGrpCount++;





Expected output :-
RowIndex   ColumnIndex  ColumnValue
1       1   John
1       2   Boone
1       3   Developer
1       4   100 
2       1   Albert
2       2   Post
2       3   Manager
2       4   500
3       1   Benjamin
3       2   Nayyar  
3       3   Developer
3       4   100 

错误:- 索引超出范围。必须为非负数并且小于集合的大小。 参数名称:索引

预期结果:

对象objMGrp是一个收集对象,它将以递增顺序存储行索引号,列索引号和列值。 我将不得不使用该对象来对值进行排序和验证。

1 个答案:

答案 0 :(得分:0)

如果仅声明了一个集合并创建了实例,则不能在该集合上使用索引0。没有元素,因此零超出了允许范围。

首先,您需要向该集合中添加一个元素

public class A
{
    // Private internal variables of this class
    List<MyGroup> objMyGrp = new List<MyGroup>();
    int iGrpCount = 0; 

    // This method adds a MyGroup instance to the collection
    public void SomeMethod()
    {
         // Some default values. You can pass parameters to this method
         // and then use parameters to initialize the MyGroup instance
         MyGroup grp = new MyGroup();
         grp.RowIndex = 0;
         grp.ColumnIndex = 0;
         grp.ObjectValue = null;

         objMyGrp.Add(grp);
         iGrpCount++;
    }

    public void SomeOtherMethod(int grpIndex)
    {
       // Now you could try to change any MyGroup instance stored in the 
       // collection to your desidered rowIndex
       if(grpIndex < iGrpCount)
          objMyGrp[grpIndex].RowIndex = 2;
    }
}