How to replace list item in best way

前端 未结 11 2221
天涯浪人
天涯浪人 2020-11-30 21:52
if (listofelements.Contains(valueFieldValue.ToString()))
{
    listofelements[listofelements.IndexOf(valueFieldValue.ToString())] = value.ToString();
}
11条回答
  •  既然无缘
    2020-11-30 22:45

    You could make it more readable and more efficient:

    string oldValue = valueFieldValue.ToString();
    string newValue = value.ToString();
    int index = listofelements.IndexOf(oldValue);
    if(index != -1)
        listofelements[index] = newValue;
    

    This asks only once for the index. Your approach uses Contains first which needs to loop all items(in the worst case), then you're using IndexOf which needs to enumerate the items again .

提交回复
热议问题