Remove item from List and get the item simultaneously
c#, list
Solution
No, as it's a breach of pure function etiquette, where a method either has a side effect, or returns a useful value (i.e. 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`:
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;
}
}
}
Problem
In C# I am trying to get an item from a list at a random index. 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. 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?