How to distinguish ReadOnlyCollection from <T> to T []?

I have a class with the ReadOnlyCollection property. I need to convert this ReadOnlyCollection to int []. How can this be done? Can this be done without repeating the collection?

+3
source share
4 answers

No, it is not possible to convert ReadOnlyCollection to an array without iterating it. This would make the collection a writable collection, breaking the read-only contract.

There are different ways to iterate through a collection, which eliminates the need to write a loop, for example using the CopyTo method.

int[] collection = new int[theObject.TheProperty.Count];
theObject.TheProperty.CopyTo(collection, 0);

Or the ToArray extension method:

int[] collection = theObject.TheProperty.ToArray();
+8
source

Of course, use the LINQ extension method myReadOnlyCollection.ToArray().

+6

. :

T[] myArray;
myCollection.CopyTo(myArray, 0);

Linq:

var myArray = myCollection.ToArray();
+5

If you use later versions the .NET framework ReadOnlyCollection<T>implements IEnumerable<T>. IEnumerable<T>has an extension method ToArray(). So you should use this extension method so ...

var readOnly = new ReadOnlyCollection<int>(new List<int>() {1,2,3,4,5});
var myArray = readOnly.ToArray();
+1
source

Source: https://habr.com/ru/post/1736574/


All Articles