[英]Remove item from List and get the item simultaneously
在C#中,我试图从列表中的随机索引处获取一个项目。 检索到它后,我希望将其删除,以便无法再选择它。 似乎我需要执行很多操作,难道没有可以从列表中提取项目的功能吗? RemoveAt(index)函数无效。 我想要一个带有返回值的商品。
我在做什么:
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”函数?
不可以,因为这违反了纯函数礼节,在这种情况下,方法要么具有副作用,要么返回有用的值(即,不仅表明错误状态),而且永远不会两者兼有。
如果您希望函数显示为原子,则可以在列表上获得一个锁,如果其他线程也使用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;
}
}
这些称为扩展方法 ,称为new List<T>().RemoveAndGetItem(0)
。
扩展方法中要考虑的事项
通过传递的索引进行异常处理之前,请检查索引是否为0以及列表的计数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.