How can I remove all the items of a list? I do not know any thing about how the items get indexed, thats why I cannot provide a better code except this..

for (int i = 0; i < _Cars.Count; i++)
            {

            }

Dani AI

Generated

A few practical follow-ups to the replies above (and to the examples from , , and ).

If you want to remove items based on a condition rather than manually looping, use the list's predicate-based bulk removal. It is simple and avoids the hazards of modifying a collection while you enumerate it:

cars.RemoveAll(c => /* condition that returns true for items to remove */);

If you must remove items while iterating, iterate from the end toward the start so removals do not shift the unvisited indexes. Note the off-by-one trap in 's snippet: start at Count-1, not Count:

for (int i = cars.Count - 1; i >= 0; i--)
{
    if (ShouldRemove(cars[i]))
        cars.RemoveAt(i);
}

Additional notes that matter in real code:

  • If the collection is data-bound (UI controls, grids), clearing or changing the underlying list may not update the UI unless you use a notifying collection (e.g., ObservableCollection<T> or BindingList<T>) or you rebind the control.
  • Clearing a List<T> resets Count to zero but does not shrink Capacity. To release the internal array memory, either assign a new list or call TrimExcess.
  • Be mindful of thread-safety: concurrent modifications require synchronization.

References:

Recommended Answers

All 5 Replies

_Cars.Clear()

Actually it's:

_Cars.Items.Clear();

;)

Actually, it's not List<T>.Clear(). List<T> doesn't have an items property.

oh f*** I saw listbox... my bad :p ur right ^^

Also, i realise you aren't going to use your code. But for future reference, if you are going to remove items from a collection in a for loop you should always start at the highest index and work back to zero. Otherwise, when you remove an item, the indexes all shift down one; the result is that you skip the next item and you risk an exception when you get to the last index because the collection is smaller than when you started.

You should use something like:

for(int i = _Cars.Count; i>=0; i--)
{
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.