I wonder if its possible to remove all the objects from the same kind from a generic List using extension methods. something like this code:
public static Remove<T>(this List<[any type]> list)
{
// some code to remove the objects of type T from the list
}
I can do this by using the following code:
public static Remove<T, K>(this List<K> list)
{
// some code to remove the objects of type T from the List<K>
}
but I want to just use on type (T), without need to specify any type K. by doing that the user can use this extension method by simply write this:
List<object> list = new List<object>();
list.Add(1);
list.Add("text");
// remove all int type objects from the list
list.Remove<int>();
a extension method which I can use to do something exactly like the above code is what I really need here.
best regards
Not sure if this will work or not…but it’s worth a shot (I can’t compile to double check):
Or if you need something a little more strict (rather than any object that can be cast to the type), you could try:
In theory, you should be good to go.
List<T>implementsIListwhich implementsIEnumerable. IList providesRemove()and IEnumerable provides the extension method.Be aware that this could most definitely produce unexpected results depending on the types in the collection. I agree with Jon Skeet…it’s most definitely ugly.