User121212 User121212 - 8 months ago 41
C# Question

How to replace list item in best way

if (listofelements.Contains(valueFieldValue.ToString()))
listofelements[listofelements.IndexOf(valueFieldValue.ToString())] = value.ToString();

I have replaced like above. Is there any other bestway to place compare than this one?


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 .