Increment a string value

别等时光非礼了梦想. 提交于 2021-02-05 11:31:06

问题


How can I increment a string value? For example:

string RECONCILIATION_COUNT;
if (thing happens) {
    RECONCILIATION_COUNT++;
}

This is normally wont work since it is not possible to increment a string variable in the same way used for int values.

RECONCILIATION_COUNT is always a number from 0-5.

I chose to declare it as a string since I am getting this value from database and i am not finding a way how to get an int value from sql.

RECONCILIATION_COUNT = Rows["RECONCILIATION_COUNT"].toString();

This is what I am using for the moment.


回答1:


It's quite weird to have a count as a String: int is by far much natural choice. Technically, you can put it as

if (thing happens)
  RECONCILIATION_COUNT = (int.Parse(RECONCILIATION_COUNT) + 1).ToString();

a better implementation is to use int:

int RECONCILIATION_COUNT;

...

if (thing happens)
  RECONCILIATION_COUNT++;

...

RECONCILIATION_COUNT = Convert.ToInt32(Rows["RECONCILIATION_COUNT"]);



回答2:


If you'd rather get your value as a string from the database, you can then parse it to an "int" later on :

Use the Int32.Parse method :

 int number = Int32.Parse(RECONCILIATION_COUNT);

Or the Int32.TryParse method :

     int number;

     bool result = Int32.TryParse(RECONCILIATION_COUNT, out number);
     if (result)
     {
        // do your increment     
     } 



回答3:


RECONCILIATION_COUNT = "" + (int32.Parse(RECONCILIATION_COUNT) + 1);

But if the variable is always a number, I'd rather declare RECONCILIATION_COUNT as int and parse the text to a number when uploading it from database.




回答4:


I think your approach here is a bit weird. You're creating a tight coupling between data types in SQL and your code and by doing this you're accumulating technical debt (workarounds) just because of DB constraints.

What i'd recommend you do is that in your repository you do the conversion from string to int and backwards (when you want to write that value in the DB).

All the answers about using the int.parse (or the like) are valid, but think about it a bit in more detail what happens if you do something like:

reconciliation_count = int.parse(reconciliation_count)++.ToString();

Break it down: - int.parse - allocates memory for a new variable which you increment - ToString - allocates memory for a NEW string which gets reasigned to your variable

There's a lot of memory going up and down and you're relying on the GC to clear up everything for you, and don't forget that strings are immutable.

However, if you follow my approach you can just assign one int variable ONCE and do whatever you want with it and then when you save it in the DB job is done.

Hope this helps.



来源:https://stackoverflow.com/questions/49938302/increment-a-string-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!