Cast generic Collection to List once, then RemoveAt multiple times

I have a generic collection of objects as a property of an object. This data comes from a sql query and api. I want to use the RemoveAt method to remove some of them efficiently. But Visual Studio complains to me that the RemoveAt method is undefined. My intuition is to cast the Collection to a List, giving me access to the RemoveAt method. I only want to cast one time, then use RemoveAt as many times as necessary. I could use the Remove(object) command, but it requires traversing the Collection to look for the object for each call, which is slower than using RemoveAt

Here is what I'm trying:

obj.stuckArray = obj.stuckArray.ToList();

After this line, I have a line of code that looks like this:

obj.stuckArray.RemoveAt(1);

Unfortunately the RemoveAt gets underlined with red and the warning from Visual Studio reads: "ICollection does not contain a definition for 'RemoveAt'"

Is it possible to cast once and RemoveAt multiple? Or is this not possible?

Jon Skeet
people
quotationmark

Just do it in three statements instead of two, using a local variable:

var list = obj.stuckArray.ToList();
list.RemoveAt(1);
obj.stuckArray = list;

That way the type of stuckArray doesn't matter as much: you only need to be able to call ToList() on it. The RemoveAt method on List<T> is fine because that's the type of list.

people

See more on this question at Stackoverflow