12

I noticed this function in a .NET project I am working on.

    private static void RemoveAllElements(ref List<int> listToBeRemoved)
    {
        foreach (var i in listToBeRemoved)
        {
            listToBeRemoved.Remove(i);
        }
    }

Is this the quickest way to remove all elements from a list? I also noticed this function doesn't catch any exceptions. Should I change this? This is in existing code.

Goks
  • 17
  • 7
abhi
  • 3,082
  • 6
  • 47
  • 73

7 Answers7

44

I don't see why you couldn't just simplify it to

listToBeRemoved.Clear();

You can see the MSDN Documentation for further details.

I don't think you need to add any exception handling logic. The Clear method internally uses Array.Clear, which as a reliability contract of Success and WillNotCorruptState. I couldn't imagine how that would throw an exception.

vcsjones
  • 138,677
  • 31
  • 291
  • 286
8
list.Clear()

See the documentation: http://msdn.microsoft.com/en-us/library/dwb5h52a.aspx

Changing the collection that you are enumerating makes the enumerator invalid, so this is very bad practice. See the remarks on List.GetEnumerator:

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.

The Clear method itself will not throw an exception, but if listToBeRemoved is null, you will get a NullReferenceException.

Jeffrey Sax
  • 10,253
  • 3
  • 29
  • 40
5

why not:

listToBeRemoved.Clear();
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Moonlight
  • 708
  • 1
  • 7
  • 18
3

How about the built-in Clear method instead?

Not only is your RemoveAllElements method completely unnecessary - it doesn't even work!

Runnning the following code will generate an InvalidOperationException with the message "Collection was modified; enumeration operation may not execute."

var list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
list.RemoveAllElements();
LukeH
  • 263,068
  • 57
  • 365
  • 409
2

The quickest way is listToBeRemoved.Clear().

Also there is no reason for that method to use ref as it does nothing to the parameter reference (just to the list referenced by the parameter). You may not be able to change this though with existing code as removing ref would require changes at the calling locations.

Kevin Brock
  • 8,874
  • 1
  • 33
  • 37
  • The funny part is that in this solution, I don't see it getting called at all. – abhi Nov 08 '11 at 19:09
  • 1
    Well, in that case, as the method is marked `private` you can be quite certain that you can excise the entire method from the class. – Kevin Brock Nov 12 '11 at 19:15
-1
static void Main (){
List<string> words = new List<string>();
words.AddRange(new[] { "banana", "plum", "peach" });

condition = words.Count;
for (int i = 0; i < condition; i++) words.RemoveAt(0);}
//it returns empty list
Sharunas Bielskis
  • 1,033
  • 1
  • 16
  • 25
  • 3
    This question asks for quickest/easiest way to remove all elements from the list. Could you explain why you think that your answer is significantly different from earlier answers? – default locale Mar 19 '15 at 05:08
  • No it is not quickest way, but only one of the possibilities. Of course quickest way to remove all items from the list is to use Clear() method. – Sharunas Bielskis Mar 19 '15 at 09:05
  • I think you need to explain in which case one should prefer your solution. Otherwise it's not clear why did you post it. – default locale Mar 19 '15 at 11:22
-1
static void Main ()
{
    List<string> words = new List<string>();
    words.AddRange(new[] { "banana", "plum", "peach" });
    words.RemoveAll(s=>s.Any());//This code returns empty list
 }
Sharunas Bielskis
  • 1,033
  • 1
  • 16
  • 25