1

如何用 C# 在 List 中搜索并编辑它的值 find 是 5,用 9 改变它的值?

List<int> myList = new List<int>() { 8, 5, 6, 2, 3 };
4

4 回答 4

1

根据情况,你可以做这样的事情

myList = myList.Select(e => e.Equals(5) ? 9 : e).ToList<int>();
于 2012-12-31T00:18:50.950 回答
0

出于某种原因,我想不出比这更好的了:

List<int> myList = new List<int>{ 8, 5, 6, 2, 3 };
while (myList.IndexOf(5)!=-1)
{
    myList[myList.IndexOf(5)] = 9;
}

您可以将其包装在 Extension 方法中并像这样使用它:

myList.Replace(5, 9);

public static class ListExt
{
    public static void Replace<T>(this List<T> list, T old, T @new)
    {
        for (int index = 0; index < list.Count; index++)
        {
            if(Equals(list[index], old))
                list[index] = @new;
        }
    }
}
于 2012-12-30T23:53:53.230 回答
0

您可以只使用一个简单的 for 循环并检查当前元素的值是否等于 5,如果是,则将其设置为 9,如下所示:

for(int i=0; i<myList.Count(); i++)
{
    if(myList[i]==5)
    {
         myList[i]=9;
    }
}
于 2012-12-30T23:56:29.163 回答
0
Find the "5" element, and change it :
short d = 0;
while ((TheList[d] != 5) && ( d < TheList.Count()))
{
   d++;
}
if (d < TheList.Count())
TheList[d] = 9;
于 2012-12-31T00:08:05.287 回答