The proposed LINQ solution using Cast
/'Select' is fine, but since you know you are working with an array here, using ConvertAll
is rather more efficienct, and just as simple.
var newArray = Array.ConvertAll(array, item => (NewType)item);
Using ConvertAll
means
a) the array is only iterated over once,
b) the operation is more optimised for arrays (does not use IEnumerator<T>
).
Don't let the Converter<TInput, TOutput>
type confuse you - it is just a simple delegate, and thus you can pass a lambda expression for it, as shown above.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…