在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