C# How to manipulate key value of dictionary dynamically

T.Zacks 3,996 Reputation points
2022-04-25T17:50:15.113+00:00

I have to store data in dictionary where key value will be excel spreadsheet row number. I am working with 3rd party spreadsheet control where I am storing TunerDto data with all spreadsheet cell tag of first column but I found 3rd party has some bug. so delete any row from spreadsheet then other row's cell tag becomes null which causing issue for me.

so for work around purpose I think I need remove dependency from cell tag of spreadsheet control and maintain this info in dictionary where dictionary key value will be spreadsheet row number because spreadsheet row number is unique.

I am storing data in dictionary where key value is excel spreadsheet row number and value field is my class instance of TunerDto class.

this way I am storing data into dictionary now.

TunerDto _rowref = new TunerDto();
CellRange usedRange = worksheet.Range[cutrows];
for (int i = 0; i < usedRange.RowCount; i++)
{
    Cell currentCell = usedRange[i, 0];
    if (currentCell.Tag != null)
    {
        _rowref = currentCell.Tag as TunerDto;
        dictRowReference.Add(usedRange[i, 0].RowIndex.ToString(), _rowref);
    }
}

The problem is suppose my spreadsheet has 10 rows with data and suddenly user cut 2nd & 3rd row and paste those rows after 5th rows. this change need to adjust or impact row number in dictionary too. so how could I do this?

Should I use dictionary for this purpose or should I use any other collection ? dictionary lookup is very first.

If user cut 2nd & 3rd row and paste after 5th rows then how could I change row number of dictionary which is the key value in dictionary ?

please guide me how to handle this scenario with dictionary or any better data structure / collection for this purpose?

looking for suggestion and concept. Thanks

Developer technologies | C#
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 78,006 Reputation points Volunteer Moderator
    2022-04-26T15:24:34.37+00:00

    because a dictionary uses a hash table, there is no order. if you want to change the key, its a delete and then add.

    if you can not detect the cut, then you probably should just rebuild the dictionary from scratch and consider it a cache,


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.