如何替换在最好的方式列表项 [英] How to replace list item in best way

查看:91
本文介绍了如何替换在最好的方式列表项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;

这对于指数只要求一次。你的方法是使用包含第一个需要循环中的所有项目(在最坏情况下),那么你使用的IndexOf 这就需要重新枚举项目。

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 .

这篇关于如何替换在最好的方式列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆