Remove an item from the list and get the item at the same time

In C #, I'm trying to get an item from a list with a random index. When it was removed, I want it to be removed so that it can no longer be selected. It seems I need a lot of operations for this, is there a function in which I can just extract an item from the list? RemoveAt (index) function is invalid. I would like to receive a return value.

What am I 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); 

Is there such a removeAndGetItem function?

+11
list c #
source share
2 answers

No, since this is a violation of the etiquette of a pure function, when a method either has a side effect or returns a useful value (i.e., it doesn’t just indicate an error state), there is never one or the other.

If you want the function to appear as atomic, you can get a lock in the list that will prevent other threads from accessing the list while it is changing, provided that 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; } } } 
+16
source share
 public static class ListExtensions { public static T RemoveAndGetItem<T>(this IList<T> list, int iIndexToRemove} { var item = list[iIndexToRemove]; list.RemoveAt(iIndexToRemove); return item; } } 

They are called extension methods , called as new List<T>().RemoveAndGetItem(0) .

What to consider in the extension method

Exception handling with the index you passed, make sure the index is 0 and the list is counted before that.

+5
source share

All Articles