2012-12-30 20 views
1

如何用C#在列表中搜索並編輯它的值 找到5,用9更改其值?用C#在列表中搜索並編輯它的值

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

使用'foreach' /'for' /'lamda' /'myList中[I]'谷歌? –

+1

如果您不需要保留列表項的順序,則可以使用'RemoveAll',並將這些元素添加回您的列表中。 RemoveAll返回刪除元素的數量,這就是如何知道要添加多少元素。 – vcsjones

+0

http://stackoverflow.com/questions/361921/list-manipulation-in-c-sharp-using-linq拼寫lambda錯誤在我的第一條評論... –

回答

0

出於某種原因,我想不出更好的東西比:

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

你可以在一個擴展方法包裝它,使用它是這樣的:

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; 
     } 
    } 
} 
0

你可以使用一個簡單的for循環,並檢查當前元素的值是否等於5,如果是,則將其設置爲9,如下所示:

for(int i=0; i<myList.Count(); i++) 
{ 
    if(myList[i]==5) 
    { 
     myList[i]=9; 
    } 
} 
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; 
+0

我不建議使用這只是因爲它感覺非常神祕,沒有冒犯,但我不明白你爲什麼不使用'for'循環? –

1

根據不同的情況,你可以做這樣的事情

myList = myList.Select(e => e.Equals(5) ? 9 : e).ToList<int>();