[英]Remove item from List and get the item simultaneously
In C# I am trying to get an item from a list at a random index. 在C#中,我试图从列表中的随机索引处获取一个项目。 When it has been retrieved I want it to be removed so that it can't be selected anymore. 检索到它后,我希望将其删除,以便无法再选择它。 It seems as if I need a lot of operations to do this, isn't there a function where I can simply extract an item from the list? 似乎我需要执行很多操作,难道没有可以从列表中提取项目的功能吗? the RemoveAt(index) function is void. RemoveAt(index)函数无效。 I would like one with a return value. 我想要一个带有返回值的商品。
What I am doing: 我在做什么:
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);
What I would like to do: 我想做的是:
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);
Does such a "removeAndGetItem" function exist? 是否存在这样的“ removeAndGetItem”函数?
No, as it's a breach of pure function etiquette, where a method either has a side effect, or returns a useful value (ie not just indicating an error state) - never both. 不可以,因为这违反了纯函数礼节,在这种情况下,方法要么具有副作用,要么返回有用的值(即,不仅表明错误状态),而且永远不会两者兼有。
If you want the function to appear atomic, you can acquire a lock on the list, which will stop other threads from accessing the list while you are modifying it, provided they also use lock
: 如果您希望函数显示为原子,则可以在列表上获得一个锁,如果其他线程也使用lock
,则该锁将阻止其他线程在修改列表时访问该列表:
public static class Extensions
{
public static T RemoveAndGet<T>(this IList<T> list, int index)
{
lock(list)
{
T value = list[index];
list.RemoveAt(index);
return value;
}
}
}
public static class ListExtensions
{
public static T RemoveAndGetItem<T>(this IList<T> list, int iIndexToRemove}
{
var item = list[iIndexToRemove];
list.RemoveAt(iIndexToRemove);
return item;
}
}
These are called extension methods , call as new List<T>().RemoveAndGetItem(0)
. 这些称为扩展方法 ,称为new List<T>().RemoveAndGetItem(0)
。
Things to consider in the extension method 扩展方法中要考虑的事项
Exception handling with the index that you pass, check that the index is withing 0 and the count of the list before doing this. 通过传递的索引进行异常处理之前,请检查索引是否为0以及列表的计数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.