Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove item from List and get the item simultaneously

Tags:

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?

like image 231
Eirik Avatar asked Mar 01 '13 09:03

Eirik


People also ask

How do I remove an item from a list?

There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.

How do you remove part of a list in Python?

In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.

What method do you use to remove an item from a list t at a specific index?

RemoveAt (Int32) Method is used to remove the element at the specified index of the List<T>. Properties of List: It is different from the arrays.


1 Answers

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;
        }
    }
}
like image 163
RoadieRich Avatar answered Oct 05 '22 23:10

RoadieRich