User121212 User121212 - 1 year ago 65
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?

Answer Source

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 .