使用扩展方法从C#中的List <T>中删除某种类型的对象?

Nim*_*gar 8 c# generics

我想知道是否可以使用扩展方法从通用List中删除相同类型的所有对象.像这样的代码:

public static Remove<T>(this List<[any type]> list)
{
    // some code to remove the objects of type T from the list
}
Run Code Online (Sandbox Code Playgroud)

我可以使用以下代码执行此操作:

public static Remove<T, K>(this List<K> list)
{
    // some code to remove the objects of type T from the List<K>
}
Run Code Online (Sandbox Code Playgroud)

但我想只使用类型(T),而不需要指定任何类型K.通过这样做,用户可以使用此扩展方法,只需写下:

List<object> list = new List<object>();
list.Add(1);
list.Add("text");

// remove all int type objects from the list
list.Remove<int>();
Run Code Online (Sandbox Code Playgroud)

我可以使用一种扩展方法来完成与上面代码完全相同的操作.

最好的祝福

Jus*_*ner 7

不知道这是否会工作或不...但它是值得一试(我不能编译仔细检查):

public static void Remove<T>(this IList list)
{
    if(list != null)
    {
        var toRemove = list.OfType<T>().ToList();

        foreach(var item in toRemove)
            list.Remove(item);
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,如果你需要的东西多一点严格的(而不是可强制转换为任何类型的对象),你可以尝试:

public static void Remove<T>(this IList list)
{
    if(list != null)
    {
        var toRemove = list.Where(i => typeof(i) == typeof(T)).ToList();

        foreach(var item in toRemove)
            list.Remove(item);
    }
}
Run Code Online (Sandbox Code Playgroud)

理论上,你应该好好去.List<T>实现的IList实现IEnumerable.IList提供了Remove()IEnumerable提供的扩展方法.

请注意,根据集合中的类型,这肯定会产生意外结果.我同意Jon Skeet ......这绝对是丑陋的.

  • @Nima:只是意识到这不会删除"Type T"的项目,但是所有项目**castable**都会删除类型T.如果传递基类,所有基类+子类元素都将被删除,例如. (2认同)