I have this code :
IList<string> stelle = stelleString.Split('-');
if (stelle.Contains("3"))
stelle.Add("8");
if (stelle.Contains("4"))
stelle.Add("6");
but seems that IList have a fixed size after a .Split() : System.NotSupportedException: Collection was of a fixed size.
How can I fix this problem?
The Split
method returns an array, and you can't resize an array.
You can create a List<string>
from the array using the ToList
extension method:
IList<string> stelle = stelleString.Split('-').ToList();
or the List<T>
constructor:
IList<string> stelle = new List<string>(stelleString.Split('-'));
Besides, you probably don't want to use the IList<T>
interface as the type of the variable, but just use the actual type of the object:
string[] stelle = stelleString.Split('-');
or:
List<string> stelle = stelleString.Split('-').ToList();
This will let you use exactly what the class can do, not limited to the IList<T>
interface, and no methods that are not supported.
string.Split
returns a string array. This would indeed have a fixed size.
You can convert it to a List<string>
by passing the result to the List<T>
constructor:
IList<string> stelle = new List<string>(stelleString.Split('-'));
Or, if available, you can use the LINQ ToList()
operator:
IList<string> stelle = stelleString.Split('-').ToList();
It has a fixed size cause string.Split returns a string[]. You need to pass the return value of split to a List<string> instance to support adding additional elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With