简体   繁体   中英

How do I can optimize inserting/replacement element in to the List<string>

I have some code:

var result = new List<string>;
...
for (var i = 0; i < level; ++i)
  if (result.ElementAtOrDefault(i) == null)
     result.Insert(i, " " + positions[i]);
  else
     result[i] += " " + positions[i];
if (result.ElementAtOrDefault(level) == null)
   result.Insert(level, " " + currentPosition);
else
   result[level] += " " + currentPosition;

Can I do this without checking element for null from i-position? I need to add a part of string in i-position. But I have "ArgumentOutOfRangeException" if element wasn't created. Also method "insert" don't replace the element but push back it.


I tried to get data from "ArgumentOutOfRangeException" (which index called this exception) but I've failed.

You can reduce using ElementAtOrDefault with adding some condition like this

int i;
for (i = 0; i < level && i < result.Count; ++i){
    //change existing items
    result[i] += " " + positions[i];
}

for (int j = 0, countAdd = level - result.Count; j < countAdd; ++j)
    //add new items
    result.Add(" " + positions[i+j]);

//add current
if (level >= result.Count)
    result.Add(" " + currentPosition);
else
    result[level] += " " + currentPosition;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM