Search code examples
c#.netopenxml

How to change list pointer for every iteration in c#?


I have a requirement where I need to store some cell values from an excel row to a list and then add it to a custom class list. But as I can't use the same object since it updates the same item twice I'm having trouble creating the editsList. I end up with editList with same set of values as this object pointer issue. Here's what I have so far.

foreach (Row r in sheetData.Elements<Row>().Skip(1))
{
    List<string> data = new List<string>();
    foreach (Cell c in r.Elements<Cell>())
    {
        if (c.DataType != null && c.DataType == CellValues.SharedString)
        {    
            int id = -1;

            if (Int32.TryParse(c.InnerText, out id))
            {
                SharedStringItem item = GetSharedStringItemById(workbookPart, id);

                if (item.Text != null)
                {
                    cellValue = item.Text.Text;
                }
                else if (item.InnerText != null)
                {
                    cellValue = item.InnerText;
                }
                else if (item.InnerXml != null)
                {
                    cellValue = item.InnerXml;
                }
            }

            data.Add(cellValue);
        }

    }
    xMLTagInfo.FileName = data[0];
    xMLTagInfo.Type = data[1];
    xMLTagInfo.ParentTag = data[2];
    xMLTagInfo.TagName = data[3];
    xMLTagInfo.AttrName = data[4];    

    editsList.Add(xMLTagInfo);    
}

Is there a way I can do this without replacing all values again with same set of values in the list? I understand it happens because I'm reusing the same object pointer. But I'm having trouble finding a solution for this.

Here's the code for my XMLTagInfo List

XMLTagInfo xMLTagInfo = new XMLTagInfo();
List<XMLTagInfo> editsList = new List<XMLTagInfo>();

Solution

  • Whatever xMLTagInfo is (it isn't shown), this should be as simple as creating a different object each row, for example:

    foreach (Row r in sheetData.Elements<Row>().Skip(1))
    {
        var xMLTagInfo = new XMLTagInfo();
        // NOT SHOWN: parse and populate xMLTagInfo
        editsList.Add(xMLTagInfo);
    }
    

    As a side note, since the list data seems to be a scratch buffer, you could probably declare that outside and reuse it, rather than creating a new List<string> for each row:

    List<string> data = new List<string>();
    foreach (Row r in sheetData.Elements<Row>().Skip(1))
    {
        var xMLTagInfo = new XMLTagInfo();
        // NOT SHOWN: parse and populate xMLTagInfo
        editsList.Add(xMLTagInfo);
        data.Clear(); // reset the scratch buffer
    }