'Why List<> implements RemoveAll, but IList<> does not

I'm refactoring my code to use IList instead of List. I used List.RemoveAll in a couple of places, and noticed that IList does not have this method at all. Is there any good reason for this?



Solution 1:[1]

Although a general software design reason was explained by Theodoros Chatzigiannakis you might be interested in a solution when you do need a RemoveAll (maybe you received an IList from a library and want to manipulate that in an easier way). There is an answer here that might interest readers: https://github.com/dotnet/core/issues/2199

Based on the answers from the Dotnet core team, I understand that the main reason is legacy, but as they said, you can easily write an extension method. An example of such an extension method (source: https://www.extensionmethod.net/csharp/icollection-t/removeall)

using System;
using System.Collections.Generic;
using System.Linq;

public static class CollectionExtensions
{
    public static void RemoveAll<T>(this ICollection<T> @this, Func<T, bool> predicate)
    {
        List<T> list = @this as List<T>;

        if (list != null)
        {
            list.RemoveAll(new Predicate<T>(predicate));
        }
        else
        {
            List<T> itemsToDelete = @this
                .Where(predicate)
                .ToList();

            foreach (var item in itemsToDelete)
            {
                @this.Remove(item);
            }
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brecht De Rooms