Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IList trouble. Fixed size?

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?

like image 350
markzzz Avatar asked Nov 08 '11 14:11

markzzz


3 Answers

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.

like image 53
Guffa Avatar answered Oct 01 '22 06:10

Guffa


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();
like image 39
Oded Avatar answered Oct 01 '22 04:10

Oded


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.

like image 41
Jehof Avatar answered Oct 01 '22 06:10

Jehof