在C#中,我試圖從列表中獲取隨機索引中的項目。當它被取回時,我希望它被刪除,以便它不能被選中。看起來好像我需要很多操作來做到這一點,是不是有一個功能,我可以簡單地從列表中提取一個項目? RemoveAt(索引)函數是無效的。我希望有一個返回值。從列表中刪除項目並同時獲取項目
我在做什麼:
List<int> numLst = new List<int>();
numLst.Add(1);
numLst.Add(2);
do
{
int index = rand.Next(numLst.Count);
int extracted = numLst[index];
// do something with extracted value...
numLst.removeAt(index);
}
while(numLst.Count > 0);
我想這樣做:
List<int> numLst = new List<int>();
numLst.Add(1);
numLst.Add(2);
do
{
int extracted = numLst.removeAndGetItem(rand.Next(numLst.Count));
// do something with this value...
}
while(numLst.Count > 0);
難道這樣的 「removeAndGetItem」 功能存在嗎?
你不得不寫你自己的 - 據我所知,只有Stack或Queue具有內置的這種功能。這需要線程安全嗎? – 2013-03-01 09:13:35
爲什麼不能得到你想要的新變量/列表? – Kaf 2013-03-01 09:14:29