[英]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.